blob: 6e877e32547a06733f27ab0a048b28622d4a81ba [file] [log] [blame]
bart032424f2008-09-27 12:26:17 +00001/** Cancel a thread that holds a lock on a mutex. */
2
3
4#include <assert.h>
5#include <pthread.h>
6#include <stdio.h>
7
8
9pthread_cond_t s_cond;
10pthread_mutex_t s_mutex1;
11pthread_mutex_t s_mutex2;
12
13
14static void* thread(void* arg)
15{
16 /* Lock s_mutex2. */
17 pthread_mutex_lock(&s_mutex2);
18 /* Inform the main thread that s_mutex2 has been locked, and wait for pthread_cancel(). */
19 pthread_mutex_lock(&s_mutex1);
20 pthread_cond_signal(&s_cond);
21 pthread_cond_wait(&s_cond, &s_mutex1);
22 return 0;
23}
24
25int main(int argc, char** argv)
26{
27 pthread_t tid;
28
29 /* Initialize synchronization objects. */
30 pthread_cond_init(&s_cond, 0);
31 pthread_mutex_init(&s_mutex1, 0);
32 pthread_mutex_init(&s_mutex2, 0);
33
34 /* Create thread. */
35 pthread_mutex_lock(&s_mutex1);
36 pthread_create(&tid, 0, &thread, 0);
37
38 /* Wait until the created thread has locked s_mutex2. */
39 pthread_cond_wait(&s_cond, &s_mutex1);
40 pthread_mutex_unlock(&s_mutex1);
41
42 /* Cancel the created thread. */
43 pthread_cancel(tid);
44
45 /* Join the created thread. */
46 pthread_join(tid, 0);
47
bart91d2fe22012-08-28 18:17:27 +000048 /* Invoke pthread_cancel() with an invalid thread ID. */
49 pthread_cancel(tid);
50
bart032424f2008-09-27 12:26:17 +000051 fprintf(stderr, "Test finished.\n");
52
53 return 0;
54}