qa_mutex_count.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 #include <core/threading/thread.h>
00025 #include <core/threading/mutex.h>
00026
00027 #include <iostream>
00028
00029
00030
00031
00032 using namespace std;
00033 using namespace fawkes;
00034
00035 #define WASTETIME \
00036 for ( unsigned int i = 0; i < 1000000; i++) { \
00037 unsigned int j; \
00038 j = i + i; \
00039 }
00040
00041
00042
00043
00044
00045
00046 class ExampleMutexCountThread : public Thread
00047 {
00048 public:
00049
00050
00051
00052
00053
00054
00055
00056 ExampleMutexCountThread(string s,
00057 Mutex *m, unsigned int *mutex_count, unsigned int *non_mutex_count,
00058 unsigned int sleep_time)
00059 : Thread("ExampMutexCountThread", Thread::OPMODE_CONTINUOUS)
00060 {
00061 this->s = s;
00062 this->sl = sl;
00063 this->slt = sleep_time;
00064 this->m = m;
00065 this->mc = mutex_count;
00066 this->nmc = non_mutex_count;
00067 }
00068
00069
00070
00071 virtual void loop()
00072 {
00073
00074
00075 unsigned int n = *nmc;
00076 n++;
00077 sleep(0);
00078 WASTETIME;
00079 *nmc = n;
00080
00081
00082
00083 if ( m != NULL ) m->lock();
00084 unsigned o = *mc;
00085 o++;
00086 sleep(0);
00087 WASTETIME;
00088 *mc = o;
00089 if ( m != NULL ) m->unlock();
00090
00091
00092 cout << s << ": mutex: " << *mc << "(non-mutex: " << *nmc << ")" << endl;
00093
00094 if ( sl ) usleep(slt);
00095
00096 test_cancel();
00097 }
00098
00099 private:
00100 string s;
00101 bool sl;
00102 unsigned int slt;
00103 Mutex *m;
00104 unsigned int *mc;
00105 unsigned int *nmc;
00106 };
00107
00108
00109 int
00110 main(int argc, char **argv)
00111 {
00112
00113 Mutex *m = new Mutex();
00114
00115 unsigned int mutex_count = 0;
00116 unsigned int non_mutex_count = 0;
00117
00118 ExampleMutexCountThread *t1 = new ExampleMutexCountThread("t1", m, &mutex_count, &non_mutex_count, 1000);
00119 ExampleMutexCountThread *t2 = new ExampleMutexCountThread("t2", m, &mutex_count, &non_mutex_count, 10000);
00120 ExampleMutexCountThread *t3 = new ExampleMutexCountThread("t3", m, &mutex_count, &non_mutex_count, 100000);
00121
00122 t1->start();
00123 t2->start();
00124 t3->start();
00125
00126
00127 t1->join();
00128 t2->join();
00129 t3->join();
00130
00131 delete t1;
00132 delete t2;
00133 delete t3;
00134 delete m;
00135 }
00136
00137
00138