1#include <pthread.h>
2#include <stdio.h>
3#include <unistd.h>
4
5static int count = 0;
6
7static void *
8thread_add_one (void *arg)
9{
10 int tmp;
11 pthread_spinlock_t *lock = (pthread_spinlock_t *) arg;
12
13 /* When do_test holds the lock for 1 sec, the two thread will be
14 in contention for the lock. */
15 if (pthread_spin_lock (lock: lock) != 0)
16 {
17 puts (s: "thread_add_one(): spin_lock failed");
18 pthread_exit (retval: (void *) 1l);
19 }
20
21 /* sleep 1s before modifying count */
22 tmp = count;
23 sleep (seconds: 1);
24 count = tmp + 1;
25
26 if (pthread_spin_unlock (lock: lock) != 0)
27 {
28 puts (s: "thread_add_one(): spin_unlock failed");
29 pthread_exit (retval: (void *) 1l);
30 }
31
32 return NULL;
33}
34
35static int
36do_test (void)
37{
38 pthread_t thr1, thr2;
39 pthread_spinlock_t lock;
40 int tmp;
41
42 if (pthread_spin_init (lock: &lock, PTHREAD_PROCESS_PRIVATE) != 0)
43 {
44 puts (s: "spin_init failed");
45 return 1;
46 }
47
48 if (pthread_spin_lock (lock: &lock) != 0)
49 {
50 puts (s: "1st spin_lock failed");
51 return 1;
52 }
53
54 if (pthread_create (newthread: &thr1, NULL, start_routine: thread_add_one, arg: (void *) &lock) != 0)
55 {
56 puts (s: "1st pthread_create failed");
57 return 1;
58 }
59
60 if (pthread_create (newthread: &thr2, NULL, start_routine: thread_add_one, arg: (void *) &lock) != 0)
61 {
62 puts (s: "2nd pthread_create failed");
63 return 1;
64 }
65
66 /* sleep 1s before modifying count */
67 tmp = count;
68 sleep (seconds: 1);
69 count = tmp + 1;
70
71 if (pthread_spin_unlock (lock: &lock) != 0)
72 {
73 puts (s: "1st spin_unlock failed");
74 return 1;
75 }
76
77 void *status;
78 if (pthread_join (th: thr1, thread_return: &status) != 0)
79 {
80 puts (s: "1st pthread_join failed");
81 return 1;
82 }
83 if (status != NULL)
84 {
85 puts (s: "failure in the 1st thread");
86 return 1;
87 }
88 if (pthread_join (th: thr2, thread_return: &status) != 0)
89 {
90 puts (s: "2nd pthread_join failed");
91 return 1;
92 }
93 if (status != NULL)
94 {
95 puts (s: "failure in the 2nd thread");
96 return 1;
97 }
98
99 if (count != 3)
100 {
101 printf (format: "count is %d, should be 3\n", count);
102 return 1;
103 }
104 return 0;
105}
106
107#define TEST_FUNCTION do_test ()
108#include "../test-skeleton.c"
109

source code of glibc/sysdeps/pthread/tst-spin4.c