Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

C의 pthread_cancel()

<시간/>

threa_cancel()은 스레드 ID로 하나의 특정 스레드를 취소하는 데 사용됩니다. 이 함수는 종료를 위해 스레드에 하나의 취소 요청을 보냅니다. pthread_cancel()의 구문은 다음과 같습니다 -

int pthread_cancel(pthread_t th);

이제 이 함수를 사용하여 스레드를 취소하는 방법을 살펴보겠습니다.

예시

#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); // wait for 1 seconds
      count++;
      if (count == 5) {
         //if the counter is 5, then request to cancel thread two and exit from current thread
         pthread_cancel(sample_thread);
         pthread_exit(NULL);
      }
   }
}
void* thread_two_func(void* p) {
   sample_thread = pthread_self(); //store the id of thread 2
   while (1) {
      printf("This is thread 2\n");
      sleep(2); // wit for 2 seconds
   }
}
main() {
   pthread_t t1, t2;
   //create two threads
   pthread_create(&t1, NULL, thread_one_func, NULL);
   pthread_create(&t2, NULL, thread_two_func, NULL);
   //wait for completing threads
   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
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2