1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <pthread.h>
 4 #include <assert.h>
 5 
 6 int lock;
 7 int val;
 8 int noassert;
 9 int badlock;
10 
11 pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
12 
13 void *lockthread(void *arg)
14 {
15 #ifdef FORCE_FAILURE
16   if (__sync_and_and_fetch(&lock, 0))
17     noassert = 1;
18 #elif defined(PTHREAD_MUTEX)
19   if (pthread_mutex_lock(&mylock))
20     abort();
21 #else
22   if (__sync_fetch_and_add(&lock, 1))
23     noassert = 1;
24 #endif
25   if (val)
26     badlock++;
27   val = 1;
28   val = 0;
29 #ifdef FORCE_FAILURE
30   (void)__sync_and_and_fetch(&lock, 0);
31 #elif defined(PTHREAD_MUTEX)
32   if (pthread_mutex_unlock(&mylock))
33     abort();
34 #else
35   (void)__sync_fetch_and_sub(&lock, 1);
36 #endif
37 }
38 
39 int main(int argc, char *argv[])
40 {
41   pthread_t t1;
42   pthread_t t2;
43 
44   if (pthread_create(&t1, NULL, lockthread, NULL))
45     abort();
46   if (pthread_create(&t2, NULL, lockthread, NULL))
47     abort();
48   if (pthread_join(t1, NULL))
49     abort();
50   if (pthread_join(t2, NULL))
51     abort();
52   assert(noassert || !badlock);
53 }