Posted By

joshuacalloway on 05/24/10


Tagged


Versions (?)

17-2


 / Published in: C++
 

  1. // Joshua Calloway
  2. // cspp51045
  3. // 17-2
  4. //
  5. #include <iostream>
  6. #include <boost/thread/thread.hpp>
  7. #include <boost/thread/mutex.hpp>
  8.  
  9. using namespace std;
  10.  
  11. class SingleThreadedPolicy {
  12. public:
  13. inline void lock(boost::mutex& mutex1) {
  14. }
  15. inline void unlock(boost::mutex& mutex1) {
  16. }
  17.  
  18. protected:
  19. SingleThreadedPolicy() {}
  20.  
  21. };
  22.  
  23.  
  24. class MultiThreadedPolicy {
  25. public:
  26. inline void lock(boost::mutex& mutex1) {
  27. //boost::mutex::scoped_lock lk(mutex1);
  28. lk = new boost::mutex::scoped_lock(mutex1);
  29. }
  30. inline void unlock(boost::mutex& mutex1) {
  31. lk->unlock();
  32. }
  33. protected:
  34. boost::mutex::scoped_lock *lk;
  35. MultiThreadedPolicy() {}
  36. };
  37.  
  38. template<class ThreadingModel = SingleThreadedPolicy>
  39. class A : public ThreadingModel {
  40.  
  41. public:
  42. static A* get_instance() {
  43. ThreadingModel::lock(st_mutex);
  44. return new A;
  45. ThreadingModel::unlock(st_mutex);
  46. }
  47.  
  48. virtual void bump(int i = 1) {
  49. ThreadingModel::lock(mutex1);
  50. //cout << "bump : " << i << " a is : " << a << endl;
  51. a += i;
  52. ThreadingModel::unlock(mutex1);
  53. }
  54.  
  55. int get_a() const { return a; }
  56. A() : a(0) {}
  57.  
  58. private:
  59. boost::mutex mutex1;
  60. static boost::mutex st_mutex;
  61.  
  62. int a;
  63. };
  64.  
  65.  
  66. template<class X>
  67. struct increment_a
  68. {
  69. X& a;
  70. int i;
  71. increment_a(X& a) : a(a), i(1) {}
  72. increment_a(X& a, int i) : a(a), i(i) {}
  73.  
  74. void operator()() {
  75. for (int j = 0; j < 100; j++) {
  76. a.bump(i);
  77. boost::thread::yield();
  78. }
  79. }
  80. };
  81.  
  82. int main() {
  83. typedef A<MultiThreadedPolicy> AA;
  84. typedef A<SingleThreadedPolicy> SS;
  85.  
  86. AA* a1 = new AA;
  87. boost::thread_group thrds;
  88. thrds.add_thread(new boost::thread(increment_a<AA>(*a1)));
  89. thrds.add_thread(new boost::thread(increment_a<AA>(*a1, 10)));
  90. thrds.add_thread(new boost::thread(increment_a<AA>(*a1, 100)));
  91.  
  92. SS* s1 = new SS;
  93. thrds.add_thread(new boost::thread(increment_a<SS>(*s1)));
  94. thrds.add_thread(new boost::thread(increment_a<SS>(*s1, 10)));
  95.  
  96. thrds.join_all();
  97. cout << "a1 : " << a1->get_a() << endl;
  98. }

Report this snippet  

You need to login to post a comment.