qa_mutex_sync.cpp
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027 #include <core/threading/thread.h>
00028 #include <core/threading/wait_condition.h>
00029 #include <core/threading/mutex.h>
00030
00031 #include <iostream>
00032 #include <string>
00033 #include <vector>
00034
00035 using namespace std;
00036 using namespace fawkes;
00037
00038
00039
00040
00041
00042
00043
00044
00045 class ExampleMutexWaitThread : public Thread
00046 {
00047 public:
00048 ExampleMutexWaitThread(string s)
00049 : Thread("ExampleMutexWaitThread", Thread::OPMODE_CONTINUOUS)
00050 {
00051 this->s = s;
00052
00053 m.lock();
00054 }
00055
00056 ~ExampleMutexWaitThread()
00057 {
00058 }
00059
00060 void wake()
00061 {
00062 m.unlock();;
00063 }
00064
00065 string getS()
00066 {
00067 return s;
00068 }
00069
00070
00071
00072 virtual void loop()
00073 {
00074 m.lock();
00075 cout << s << ": my turn" << endl;
00076
00077 m.unlock();
00078 }
00079
00080 private:
00081 Mutex m;
00082 string s;
00083
00084 };
00085
00086 class ExampleMutexWaitStarterThread : public Thread
00087 {
00088 public:
00089 ExampleMutexWaitStarterThread()
00090 : Thread("ExampleMutexWaitStarterThread", Thread::OPMODE_CONTINUOUS)
00091 {
00092 threads.clear();
00093 }
00094
00095 void wakeThreads()
00096 {
00097 vector< ExampleMutexWaitThread * >::iterator tit;
00098 for (tit = threads.begin(); tit != threads.end(); ++tit) {
00099 cout << "Waking thread " << (*tit)->getS() << endl;
00100 (*tit)->wake();
00101 }
00102 }
00103
00104 void addThread(ExampleMutexWaitThread *t)
00105 {
00106 threads.push_back(t);
00107 }
00108
00109
00110 virtual void loop()
00111 {
00112 sleep(2423423);
00113 wakeThreads();
00114 }
00115
00116 private:
00117 vector< ExampleMutexWaitThread * > threads;
00118 };
00119
00120
00121
00122
00123 int
00124 main(int argc, char **argv)
00125 {
00126
00127 ExampleMutexWaitThread *t1 = new ExampleMutexWaitThread("t1");
00128 ExampleMutexWaitThread *t2 = new ExampleMutexWaitThread("t2");
00129 ExampleMutexWaitThread *t3 = new ExampleMutexWaitThread("t3");
00130
00131 ExampleMutexWaitStarterThread *st = new ExampleMutexWaitStarterThread();
00132 st->addThread( t1 );
00133 st->addThread( t2 );
00134 st->addThread( t3 );
00135
00136 t1->start();
00137 t2->start();
00138 t3->start();
00139 st->start();
00140
00141 t1->join();
00142 t2->join();
00143 t3->join();
00144 st->join();
00145
00146 delete st;
00147 delete t3;
00148 delete t2;
00149 delete t1;
00150
00151 return 0;
00152 }
00153
00154
00155