Home | History | Annotate | Download | only in tests
      1 /// Test program that uses the QAtomicInt class.
      2 
      3 #ifndef _GNU_SOURCE
      4 #define _GNU_SOURCE
      5 #endif
      6 
      7 #include "config.h"
      8 #include <QAtomicInt>     // class QAtomicInt
      9 #include <cassert>
     10 #include <cstdio>         // fprintf()
     11 #include <cstdlib>        // atoi()
     12 #include <new>
     13 #include <pthread.h>      // pthread_barrier_t
     14 #include <vector>
     15 
     16 
     17 static pthread_barrier_t s_barrier;
     18 static QAtomicInt* s_pAtomicInt;
     19 
     20 
     21 void* thread_func(void* pArg)
     22 {
     23   const int iArg = *reinterpret_cast<int*>(pArg);
     24 
     25   pthread_barrier_wait(&s_barrier);
     26 
     27   while (! s_pAtomicInt->testAndSetOrdered(iArg, iArg + 1))
     28     ;
     29 
     30   return NULL;
     31 }
     32 
     33 int main(int argc, char** argv)
     34 {
     35   int i;
     36   const int n_threads = 10;
     37   std::vector<int>       thread_arg(n_threads);
     38   std::vector<pthread_t> tid(n_threads);
     39 
     40   fprintf(stderr, "Start of test.\n");
     41 
     42   pthread_barrier_init(&s_barrier, 0, n_threads);
     43   s_pAtomicInt = new QAtomicInt();
     44   for (i = 0; i < n_threads; i++)
     45   {
     46     thread_arg[i] = i;
     47     pthread_create(&tid[i], 0, thread_func, &thread_arg[i]);
     48   }
     49   for (i = 0; i < n_threads; i++)
     50   {
     51     pthread_join(tid[i], NULL);
     52   }
     53   pthread_barrier_destroy(&s_barrier);
     54 
     55   if (*s_pAtomicInt == n_threads)
     56     fprintf(stderr, "Test successful.\n");
     57   else
     58     fprintf(stderr, "Test failed: counter = %d, should be %d\n",
     59             static_cast<int>(*s_pAtomicInt), n_threads);
     60 
     61   delete s_pAtomicInt;
     62   s_pAtomicInt = 0;
     63 
     64   return 0;
     65 }
     66