#include #include #include #include #include #include #include pthread_t t1; pthread_t t2; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; int c; void cancellation(void *nothing) { if (pthread_mutex_lock(&m)) { printf("cancellation: lock error.\n"); exit(1); } c++; if (pthread_mutex_unlock(&m)) { printf("cancellation: unlock error.\n"); exit(1); } } void *thread1(void *nothing) { pthread_cleanup_push(cancellation, NULL); while (1) { usleep(10); } // never reached pthread_cleanup_pop(NULL); exit(5); return NULL; } void *thread2(void *nothing) { // wait until t1 is created pthread_mutex_lock(&m); pthread_mutex_unlock(&m); if (pthread_cancel(t1) != 0) { printf("cancel error.\n"); exit(1); } if (pthread_join(t1, NULL)) { printf("join t1 error.\n"); exit(1); } pthread_exit(NULL); return NULL; } int main(void) { int i = 0; struct timeval tv1, tv2, dt; printf("pid: %d\n", getpid()); gettimeofday(&tv1, NULL); c=0; while (1) { if (pthread_mutex_lock(&m)) { printf("lock error.\n"); exit(1); } if ( pthread_create(&t1, NULL, thread1, NULL) || pthread_create(&t2, NULL, thread2, NULL)) { printf("create error.\n"); exit(1); } if (pthread_mutex_unlock(&m)) { printf("unlock error.\n"); exit(1); } if (pthread_join(t2, NULL)) { printf("join t2 error.\n"); exit(1); } if (i++ % 1000 == 0) { gettimeofday(&tv2, NULL); timersub( &tv2, &tv1, &dt ); printf("i=%d, c=%d, dt=%ld.%06ld\n", i, c, dt.tv_sec, dt.tv_usec); tv1 = tv2; } } return 0; }