pthread_cancel(thread_id) gửi yêu cầu hủy thread. Thread bị hủy tại cancellation point (như sleep, wait).
Cú pháp
int pthread_cancel(pthread_t th);
Ví dụ: Thread 1 hủy thread 2 sau 5 lần in
int count = 0;
pthread_t t2_id;
void* thread1(void* p) {
while(1) {
printf("Thread 1\n"); sleep(1);
if (++count == 5) {
pthread_cancel(t2_id);
pthread_exit(NULL);
}
}
}
void* thread2(void* p) {
t2_id = pthread_self();
while(1) { printf("Thread 2\n"); sleep(2); }
}
main() {
pthread_t t1, t2;
pthread_create(&t1, NULL, thread1, NULL);
pthread_create(&t2, NULL, thread2, NULL);
pthread_join(t1, NULL); pthread_join(t2, NULL);
}