1 /* Test whether detached threads are handled properly. */
4 #include <limits.h> /* PTHREAD_STACK_MIN */
10 static int s_finished_count
; /* protected by s_mutex */
11 static pthread_mutex_t s_mutex
;
12 static pthread_cond_t s_cond
;
14 static void increment_finished_count()
16 pthread_mutex_lock(&s_mutex
);
18 pthread_cond_signal(&s_cond
);
19 pthread_mutex_unlock(&s_mutex
);
22 static void* thread_func1(void* arg
)
24 write(STDOUT_FILENO
, ".", 1);
25 increment_finished_count();
29 static void* thread_func2(void* arg
)
31 pthread_detach(pthread_self());
32 write(STDOUT_FILENO
, ".", 1);
33 increment_finished_count();
37 int main(int argc
, char** argv
)
39 const int count1
= argc
> 1 ? atoi(argv
[1]) : 100;
40 const int count2
= argc
> 2 ? atoi(argv
[2]) : 100;
45 pthread_mutex_init(&s_mutex
, 0);
46 pthread_cond_init(&s_cond
, 0);
48 pthread_attr_init(&attr
);
49 pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
);
50 assert(pthread_attr_getdetachstate(&attr
, &detachstate
) == 0);
51 assert(detachstate
== PTHREAD_CREATE_DETACHED
);
52 pthread_attr_setstacksize(&attr
, PTHREAD_STACK_MIN
+ 4096);
53 // Create count1 detached threads by setting the "detached" property via
55 for (i
= 0; i
< count1
; i
++)
58 pthread_create(&thread
, &attr
, thread_func1
, NULL
);
60 // Create count2 detached threads by letting the threads detach themselves.
61 pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_JOINABLE
);
62 assert(pthread_attr_getdetachstate(&attr
, &detachstate
) == 0);
63 assert(detachstate
== PTHREAD_CREATE_JOINABLE
);
64 for (i
= 0; i
< count2
; i
++)
67 pthread_create(&thread
, &attr
, thread_func2
, NULL
);
69 pthread_attr_destroy(&attr
);
71 // Wait until all detached threads have written their output to stdout.
72 pthread_mutex_lock(&s_mutex
);
73 while (s_finished_count
< count1
+ count2
) {
74 const int ret
= pthread_cond_wait(&s_cond
, &s_mutex
);
77 pthread_mutex_unlock(&s_mutex
);
79 pthread_cond_destroy(&s_cond
);
80 pthread_mutex_destroy(&s_mutex
);
82 write(STDOUT_FILENO
, "\n", 1);
83 fprintf(stderr
, "Done.\n");