Home | History | Annotate | Download | only in tests
      1 /// Qt4 semaphore test.
      2 
      3 #ifndef _GNU_SOURCE
      4 #define _GNU_SOURCE
      5 #endif
      6 
      7 #include <QThread>           // class QMutex
      8 #include <QSemaphore>        // class QSemaphore
      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 QSemaphore* s_pSema;
     18 static int s_iterations;
     19 static int s_counter;
     20 
     21 
     22 class IncThread: public QThread
     23 {
     24   virtual void run();
     25 };
     26 
     27 void IncThread::run()
     28 {
     29   int i;
     30 
     31   pthread_barrier_wait(&s_barrier);
     32   for (i = s_iterations; i > 0; i--)
     33   {
     34     s_pSema->acquire();
     35     s_counter++;
     36     s_pSema->release();
     37   }
     38 }
     39 
     40 int main(int argc, char** argv)
     41 {
     42   int i;
     43   const int n_threads = 10;
     44   std::vector<QThread*> tid(n_threads);
     45 
     46   s_iterations = argc > 1 ? atoi(argv[1]) : 1000;
     47 
     48   fprintf(stderr, "Start of test.\n");
     49 
     50   {
     51     // Stack-allocated semaphore.
     52     QSemaphore S(1);
     53     S.acquire();
     54     S.release();
     55     S.acquire();
     56     S.release();
     57   }
     58 
     59   pthread_barrier_init(&s_barrier, 0, n_threads);
     60   s_pSema = new QSemaphore(1);
     61   for (i = 0; i < n_threads; i++)
     62   {
     63     tid[i] = new IncThread;
     64     tid[i]->start();
     65   }
     66   for (i = 0; i < n_threads; i++)
     67   {
     68     tid[i]->wait();
     69     delete tid[i];
     70   }
     71   delete s_pSema;
     72   s_pSema = 0;
     73   pthread_barrier_destroy(&s_barrier);
     74 
     75   if (s_counter == n_threads * s_iterations)
     76     fprintf(stderr, "Test successful.\n");
     77   else
     78     fprintf(stderr, "Test failed: counter = %d, should be %d\n",
     79             s_counter, n_threads * s_iterations);
     80 
     81   return 0;
     82 }
     83