pthread_cancel() ফাংশনটি থ্রেড ID দিয়ে একটি নির্দিষ্ট থ্রেড বাতিল করার অনুরোধ পাঠায়।
সিনট্যাক্স: int pthread_cancel(pthread_t th);
উদাহরণ
#include <stdio.h>
#include <unistd.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);
}
}
int 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);
return 0;
}
আউটপুট
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 continues after thread 1 exits)