• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /// Qt4 reader-writer lock test.
2 
3 #ifndef _GNU_SOURCE
4 #define _GNU_SOURCE
5 #endif
6 
7 #include <QThread>               // class QThread
8 #include <QReadWriteLock>        // class QReadWriteLock
9 #include <cstdio>                // fprintf()
10 #include <cstdlib>               // atoi()
11 #include <new>
12 #include <pthread.h>             // pthread_barrier_t
13 #include <vector>
14 
15 
16 static pthread_barrier_t s_barrier;
17 static QReadWriteLock* s_pRWlock;
18 static int s_iterations;
19 static int s_counter;
20 
21 
22 class IncThread: public QThread
23 {
24 public:
25   IncThread();
26   virtual ~IncThread();
27 
28 private:
29   virtual void run();
30 };
31 
IncThread()32 IncThread::IncThread()
33 { }
34 
~IncThread()35 IncThread::~IncThread()
36 { }
37 
run()38 void IncThread::run()
39 {
40   int i;
41 
42   pthread_barrier_wait(&s_barrier);
43   for (i = s_iterations; i > 0; i--)
44   {
45     s_pRWlock->lockForWrite();
46     s_counter++;
47     s_pRWlock->unlock();
48   }
49 }
50 
main(int argc,char ** argv)51 int main(int argc, char** argv)
52 {
53   int i;
54   const int n_threads = 10;
55   std::vector<QThread*> tid(n_threads);
56 
57   s_iterations = argc > 1 ? atoi(argv[1]) : 1000;
58 
59   fprintf(stderr, "Start of test.\n");
60 
61   {
62     // Stack-allocated reader-writer lock.
63     QReadWriteLock RWL;
64     RWL.lockForRead();
65     RWL.unlock();
66     RWL.lockForWrite();
67     RWL.unlock();
68   }
69 
70   pthread_barrier_init(&s_barrier, 0, n_threads);
71   s_pRWlock = new QReadWriteLock();
72   for (i = 0; i < n_threads; i++)
73   {
74     tid[i] = new IncThread;
75     tid[i]->start();
76   }
77   for (i = 0; i < n_threads; i++)
78   {
79     tid[i]->wait();
80     delete tid[i];
81   }
82   delete s_pRWlock;
83   s_pRWlock = 0;
84   pthread_barrier_destroy(&s_barrier);
85 
86   if (s_counter == n_threads * s_iterations)
87     fprintf(stderr, "Test successful.\n");
88   else
89     fprintf(stderr, "Test failed: counter = %d, should be %d\n",
90             s_counter, n_threads * s_iterations);
91 
92   return 0;
93 }
94