Home | History | Annotate | Download | only in tests
      1 /** 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 
      9 pthread_cond_t  s_cond;
     10 pthread_mutex_t s_mutex1;
     11 pthread_mutex_t s_mutex2;
     12 
     13 
     14 static 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 
     25 int 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 
     48   /* Invoke pthread_cancel() with an invalid thread ID. */
     49   pthread_cancel(tid);
     50 
     51   fprintf(stderr, "Test finished.\n");
     52 
     53   return 0;
     54 }
     55