blob: a0fad5d5d757310d1e3be36ff0d948241a395e9f [file] [log] [blame]
sewardjb4112022007-11-09 22:49:28 +00001
2/* Expect 5 errors total (4 re cvs, 1 re exiting w/lock.).
3 Tests passing bogus mutexes to pthread_cond_wait. */
4#define _GNU_SOURCE 1 /* needed by glibc <= 2.3 for pthread_rwlock_* */
5#include <pthread.h>
6#include <assert.h>
7#include <unistd.h>
8#include <semaphore.h>
9
10pthread_mutex_t mx[4];
11pthread_cond_t cv;
12pthread_rwlock_t rwl;
13
14sem_t quit_now;
15
16void* rescue_me ( void* uu )
17{
18 /* wait for, and unblock, the first wait */
19 sleep(1);
20 pthread_cond_signal( &cv );
21
22 /* wait for, and unblock, the second wait */
23 sleep(1);
24 pthread_cond_signal( &cv );
25
26 /* wait for, and unblock, the third wait */
27 sleep(1);
28 pthread_cond_signal( &cv );
29
30 /* wait for, and unblock, the fourth wait */
31 sleep(1);
32 pthread_cond_signal( &cv );
33
34 sem_wait( &quit_now );
35 return NULL;
36}
37
38void* grab_the_lock ( void* uu )
39{
40 int r= pthread_mutex_lock( &mx[2] ); assert(!r);
41 sem_wait( &quit_now );
42 r= pthread_mutex_unlock( &mx[2] ); assert(!r);
43 return NULL;
44}
45
46int main ( void )
47{
48 int r;
49 pthread_t my_rescuer, grabber;
50
51 r= pthread_mutex_init(&mx[0], NULL); assert(!r);
52 r= pthread_mutex_init(&mx[1], NULL); assert(!r);
53 r= pthread_mutex_init(&mx[2], NULL); assert(!r);
54 r= pthread_mutex_init(&mx[3], NULL); assert(!r);
55
56 r= pthread_cond_init(&cv, NULL); assert(!r);
57 r= pthread_rwlock_init(&rwl, NULL); assert(!r);
58
59 r= sem_init( &quit_now, 0,0 ); assert(!r);
60
61 r= pthread_create( &grabber, NULL, grab_the_lock, NULL ); assert(!r);
62 sleep(1); /* let the grabber get there first */
63
64 r= pthread_create( &my_rescuer, NULL, rescue_me, NULL ); assert(!r);
65 /* Do stupid things and hope that rescue_me gets us out of
66 trouble */
67
68 /* mx is bogus */
69 r= pthread_cond_wait(&cv, (pthread_mutex_t*)(1 + (char*)&mx[0]) );
70
71 /* mx is not locked */
72 r= pthread_cond_wait(&cv, &mx[0]);
73
74 /* wrong flavour of lock */
75 r= pthread_cond_wait(&cv, (pthread_mutex_t*)&rwl );
76
77 /* mx is held by someone else. */
78 r= pthread_cond_wait(&cv, &mx[2] );
79
80 r= sem_post( &quit_now ); assert(!r);
81 r= sem_post( &quit_now ); assert(!r);
82
83 r= pthread_join( my_rescuer, NULL ); assert(!r);
84 r= pthread_join( grabber, NULL ); assert(!r);
85 return 0;
86}