1
2#include <pthread.h>
3#include <stdio.h>
4#include <stdlib.h>
5#include <assert.h>
6#include <unistd.h>
7
8/* Test of the mechanism for showing all locks held by a thread.  Test
9   the case where the earlier thread held, at the time of the access,
10   some locks, at least one of which is deleted by the time the second
11   access (the race) happens.  This causes problems for Helgrind's
12   error reporting mechanism in that it can no longer show the deleted
13   lock in the error message.x */
14
15pthread_mutex_t mx1a;
16pthread_mutex_t mx1b;
17pthread_mutex_t mx2a;
18pthread_mutex_t mx2b;
19
20int x = 0;
21
22void* child_fn1 ( void* arg )
23{
24   int r;
25   // We are the first-accessing thread.  Take and release two locks
26   // and then destroy one of them.
27   r= pthread_mutex_lock(&mx1a);  assert(!r);
28   r= pthread_mutex_lock(&mx1b);  assert(!r);
29   x = 1;
30   r= pthread_mutex_unlock(&mx1b);  assert(!r);
31   r= pthread_mutex_unlock(&mx1a);  assert(!r);
32   r= pthread_mutex_destroy(&mx1a);  assert(!r);
33   sleep(1);
34   return NULL;
35}
36
37void* child_fn2 ( void* arg )
38{
39   int r;
40   // We are the second-accessing thread.  Take and release
41   // our two locks, but don't otherwise mess with them.
42   sleep(1);
43   r= pthread_mutex_lock(&mx2a);  assert(!r);
44   r= pthread_mutex_lock(&mx2b);  assert(!r);
45   x = 1;
46   r= pthread_mutex_unlock(&mx2b);  assert(!r);
47   r= pthread_mutex_unlock(&mx2a);  assert(!r);
48   return NULL;
49}
50
51int main ( int argc, char** argv )
52{
53   pthread_t child1, child2;
54   int r;
55
56   r= pthread_mutex_init(&mx1a, NULL);  assert(!r);
57   r= pthread_mutex_init(&mx1b, NULL);  assert(!r);
58   r= pthread_mutex_init(&mx2a, NULL);  assert(!r);
59   r= pthread_mutex_init(&mx2b, NULL);  assert(!r);
60
61   r= pthread_create(&child2, NULL, child_fn2, NULL);  assert(!r);
62   r= pthread_create(&child1, NULL, child_fn1, NULL);  assert(!r);
63
64   r= pthread_join(child1, NULL);  assert(!r);
65   r= pthread_join(child2, NULL);  assert(!r);
66
67   // don't destroy mx1a; it's already destroyed.
68   r= pthread_mutex_destroy(&mx1b);  assert(!r);
69   r= pthread_mutex_destroy(&mx2a);  assert(!r);
70   r= pthread_mutex_destroy(&mx2b);  assert(!r);
71
72   return 0;
73}
74