blob: c20b163f2c66204c99e3a7a1184c256692ecb7ed [file] [log] [blame]
bart3d622d32008-07-07 16:57:38 +00001/// Qt4 mutex test.
2
3#ifndef _GNU_SOURCE
4#define _GNU_SOURCE
5#endif
6
bart62f54e42008-07-28 11:35:10 +00007#include "config.h"
bart4f6aa5c2008-08-02 09:28:39 +00008#include <QMutex> // class QMutex
9#include <QThread> // class QThread
bart480e22c2008-07-07 18:35:55 +000010#include <cassert>
barta324c102008-07-07 17:19:17 +000011#include <cstdio> // fprintf()
12#include <cstdlib> // atoi()
bart3d622d32008-07-07 16:57:38 +000013#include <new>
barta324c102008-07-07 17:19:17 +000014#include <pthread.h> // pthread_barrier_t
bart3d622d32008-07-07 16:57:38 +000015#include <vector>
16
17
18static pthread_barrier_t s_barrier;
19static QMutex* s_pMutex;
20static int s_iterations;
21static int s_counter;
22
23
24class IncThread: public QThread
25{
26 virtual void run();
27};
28
29void IncThread::run()
30{
31 int i;
32
33 pthread_barrier_wait(&s_barrier);
34 for (i = s_iterations; i > 0; i--)
35 {
36 s_pMutex->lock();
37 s_counter++;
38 s_pMutex->unlock();
39 }
40}
41
42int main(int argc, char** argv)
43{
44 int i;
45 const int n_threads = 10;
46 std::vector<QThread*> tid(n_threads);
47
48 s_iterations = argc > 1 ? atoi(argv[1]) : 1000;
49
50 fprintf(stderr, "Start of test.\n");
51
52 {
53 // Stack-allocated mutex.
54 QMutex M(QMutex::Recursive);
55 M.lock();
bart480e22c2008-07-07 18:35:55 +000056 assert(M.tryLock());
bart3d622d32008-07-07 16:57:38 +000057 M.unlock();
58 M.unlock();
59 }
bart62f54e42008-07-28 11:35:10 +000060#if defined(HAVE_QTCORE_QMUTEX_TRYLOCK_INT)
bart480e22c2008-07-07 18:35:55 +000061 {
62 QMutex M(QMutex::NonRecursive);
63 assert(M.tryLock(1));
64 assert(! M.tryLock(1));
65 M.unlock();
66 }
bart62f54e42008-07-28 11:35:10 +000067#endif
bart3d622d32008-07-07 16:57:38 +000068
69 pthread_barrier_init(&s_barrier, 0, n_threads);
70 s_pMutex = new QMutex();
71 for (i = 0; i < n_threads; i++)
72 {
73 tid[i] = new IncThread;
74 tid[i]->start();
75 }
76 for (i = 0; i < n_threads; i++)
77 {
78 tid[i]->wait();
79 delete tid[i];
80 }
81 delete s_pMutex;
82 s_pMutex = 0;
83 pthread_barrier_destroy(&s_barrier);
84
85 if (s_counter == n_threads * s_iterations)
86 fprintf(stderr, "Test successful.\n");
87 else
88 fprintf(stderr, "Test failed: counter = %d, should be %d\n",
89 s_counter, n_threads * s_iterations);
90
91 return 0;
92}