1 /** pthread_spinloc_t test. */
2 
3 
4 /* Make sure pthread_spinlock_t is available when compiling with older glibc
5  * versions (2.3 or before).
6  */
7 #define _GNU_SOURCE
8 
9 #include <pthread.h>
10 #include <stdio.h>   /* fprintf() */
11 #include <stdlib.h>  /* atoi() */
12 
13 
14 static pthread_barrier_t  s_barrier;
15 static pthread_spinlock_t s_spinlock;
16 static int s_iterations;
17 static int s_counter;
18 
19 
20 static void* thread_func(void* arg)
21 {
22   int i;
23 
24   pthread_barrier_wait(&s_barrier);
25   for (i = s_iterations; i > 0; i--)
26   {
27     pthread_spin_lock(&s_spinlock);
28     s_counter++;
29     pthread_spin_unlock(&s_spinlock);
30   }
31   return 0;
32 }
33 
34 int main(int argc, char** argv)
35 {
36   int i;
37   const int n_threads = 10;
38   pthread_t tid[n_threads];
39 
40   s_iterations = argc > 1 ? atoi(argv[1]) : 1000;
41 
42   fprintf(stderr, "Start of test.\n");
43   pthread_barrier_init(&s_barrier, 0, n_threads);
44   pthread_spin_init(&s_spinlock, 0);
45   for (i = 0; i < n_threads; i++)
46     pthread_create(&tid[i], 0, thread_func, 0);
47   for (i = 0; i < n_threads; i++)
48     pthread_join(tid[i], 0);
49   pthread_spin_destroy(&s_spinlock);
50   pthread_barrier_destroy(&s_barrier);
51   if (s_counter == n_threads * s_iterations)
52     fprintf(stderr, "Test successful.\n");
53   else
54     fprintf(stderr, "Test failed: counter = %d, should be %d\n",
55             s_counter, n_threads * s_iterations);
56   return 0;
57 }
58