首頁 > 後端開發 > C++ > 在C語言中,pthread_cancel()函數的意思是取消一個線程

在C語言中,pthread_cancel()函數的意思是取消一個線程

WBOY
發布: 2023-09-15 10:13:06
轉載
1160 人瀏覽過

在C語言中,pthread_cancel()函數的意思是取消一個線程

The threa_cancel() is used to cancel one particular thread by the thread id. This function sends one cancellation request to the thread for termination. The syntax of the pthread_cancel(low) 3thread) like −

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</p><p>");
      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</p><p>");
      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
登入後複製

以上是在C語言中,pthread_cancel()函數的意思是取消一個線程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板