1 // commit 12e1e324683a1d381b7f15dd36c99b37dd44d940 2015-04-10
2 // robust mutex should work with detached threads too
3 #include <pthread.h>
4 #include <string.h>
5 #include <errno.h>
6 #include <time.h>
7 #include "test.h"
8
9 #define TX(r,f,x) ( ((r)=(f))==x || \
10 (t_error(#f" failed: (pshared==%d) got %d \"%s\" want %d \"%s\"\n", pshared, r, strerror(r), x, strerror(x)), 0) )
11 #define T(r,f) TX(r,f,0)
12
13 static pthread_barrier_t barrier2;
14 static int pshared;
15
start_lock(void * arg)16 static void *start_lock(void *arg)
17 {
18 pthread_mutex_lock(arg);
19 pthread_barrier_wait(&barrier2);
20 return 0;
21 }
22
f()23 static void f()
24 {
25 pthread_t td;
26 int r;
27 pthread_mutexattr_t mtx_a;
28 pthread_mutex_t mtx;
29 struct timespec ts;
30
31 T(r, pthread_barrier_init(&barrier2, 0, 2));
32 T(r, pthread_mutexattr_init(&mtx_a));
33 T(r, pthread_mutexattr_setrobust(&mtx_a, PTHREAD_MUTEX_ROBUST));
34 if (pshared)
35 T(r, pthread_mutexattr_setpshared(&mtx_a, PTHREAD_PROCESS_SHARED));
36 T(r, pthread_mutex_init(&mtx, &mtx_a));
37 T(r, pthread_create(&td, 0, start_lock, &mtx));
38 T(r, pthread_detach(td));
39 pthread_barrier_wait(&barrier2);
40 pthread_barrier_destroy(&barrier2);
41
42 // enough time to ensure that the detached thread is dead
43 clock_gettime(CLOCK_REALTIME, &ts);
44 ts.tv_nsec += 100*1000*1000;
45 if (ts.tv_nsec >= 1000*1000*1000) {
46 ts.tv_sec++;
47 ts.tv_nsec -= 1000*1000*1000;
48 }
49
50 TX(r, pthread_mutex_timedlock(&mtx, &ts), EOWNERDEAD);
51 }
52
main(void)53 int main(void)
54 {
55 // test non-pshared and pshared robust mutexes as well
56 f();
57 pshared = 1;
58 f();
59 return t_status;
60 }
61