Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

pthread_cancel() ใน C


pthread_cancel() ใช้ยกเลิก thread เฉพาะตัวด้วย thread ID ส่ง cancellation request ให้ thread เพื่อ termination ไวยากรณ์:

int pthread_cancel(pthread_t th);

ดูวิธียกเลิก thread ด้วยฟังก์ชันนี้

ตัวอย่าง

#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <pthread.h> int count = 0; pthread_t sample_thread; void* thread_one_func(void* p) { while(1) { printf("This is thread 1\n"); sleep(1); count++; if(count == 5) { pthread_cancel(sample_thread); pthread_exit(NULL); } } } void* thread_two_func(void* p) { sample_thread = pthread_self(); while(1) { printf("This is thread 2\n"); sleep(2); } } main() { pthread_t t1, t2; pthread_create(&t1, NULL, thread_one_func, NULL); pthread_create(&t2, NULL, thread_two_func, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); }

ผลลัพธ์

This is thread 2 This is thread 1 This is thread 1 This is thread 2 This is thread 1 This is thread 1 This is thread 1 This is thread 2 ... (thread 2 ถูก cancel หลัง count=5)