blob: db9cf24e7c170c55308e519febd4ddcb5c697fec [file] [log] [blame]
bart4f578bf2008-07-07 18:35:13 +00001/// Qt4 reader-writer lock test.
2
3#ifndef _GNU_SOURCE
4#define _GNU_SOURCE
5#endif
6
bart4f6aa5c2008-08-02 09:28:39 +00007#include <QThread> // class QThread
8#include <QReadWriteLock> // class QReadWriteLock
bart4f578bf2008-07-07 18:35:13 +00009#include <cstdio> // fprintf()
10#include <cstdlib> // atoi()
11#include <new>
12#include <pthread.h> // pthread_barrier_t
13#include <vector>
14
15
16static pthread_barrier_t s_barrier;
17static QReadWriteLock* s_pRWlock;
18static int s_iterations;
19static int s_counter;
20
21
22class IncThread: public QThread
23{
bartaef57db2009-08-18 20:29:26 +000024public:
25 IncThread();
26 virtual ~IncThread();
27
28private:
bart4f578bf2008-07-07 18:35:13 +000029 virtual void run();
30};
31
bartaef57db2009-08-18 20:29:26 +000032IncThread::IncThread()
33{ }
34
35IncThread::~IncThread()
36{ }
37
bart4f578bf2008-07-07 18:35:13 +000038void 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
51int 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.
bart39186902008-07-08 08:51:51 +000063 QReadWriteLock RWL;
bart4f578bf2008-07-07 18:35:13 +000064 RWL.lockForRead();
65 RWL.unlock();
bart4f578bf2008-07-07 18:35:13 +000066 RWL.lockForWrite();
bart4f578bf2008-07-07 18:35:13 +000067 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}