1 /// Qt4 mutex test. 2 3 #ifndef _GNU_SOURCE 4 #define _GNU_SOURCE 5 #endif 6 7 #include "config.h" 8 #include <QMutex> // class QMutex 9 #include <QThread> // class QThread 10 #include <cassert> 11 #include <cstdio> // fprintf() 12 #include <cstdlib> // atoi() 13 #include <new> 14 #include <pthread.h> // pthread_barrier_t 15 #include <vector> 16 17 18 static pthread_barrier_t s_barrier; 19 static QMutex* s_pMutex; 20 static int s_iterations; 21 static int s_counter; 22 23 24 class IncThread: public QThread 25 { 26 virtual void run(); 27 }; 28 29 void 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 42 int 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(); 56 assert(M.tryLock()); 57 M.unlock(); 58 M.unlock(); 59 } 60 #if defined(HAVE_QTCORE_QMUTEX_TRYLOCK_INT) 61 { 62 QMutex M(QMutex::NonRecursive); 63 assert(M.tryLock(1)); 64 assert(! M.tryLock(1)); 65 M.unlock(); 66 } 67 #endif 68 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 } 93