簡體   English   中英

pthread_cancel不會取消線程— C ++

[英]pthread_cancel is not canceling a thread — C++

我正在嘗試從main取消線程。 它不會立即取消,但大約需要4秒鍾。 這應該是因為我已將其取消類型設置為與默認值(延遲)異步。 為什么?

#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
using namespace std;


void *thread_function(void *arg);
int main()
{
  int res;
  pthread_t a_thread;
  res = pthread_create(&a_thread, NULL, thread_function, NULL);
  sleep(5);
  printf("Canceling thread...\n");
  res = pthread_cancel(a_thread);
  printf("Waiting for thread to finish...\n");
  res = pthread_join(a_thread, NULL);
  pthread_exit(0);
}



void *thread_function(void *arg)
{
  int i, res;
  res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  res = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  printf("thread_function is running\n");
  for(i = 0; i < 17; i++) {
    pthread_yield();
    printf("Thread is still running (%d)...\n", i);
    sleep(1);
  }
  pthread_exit(0);
}

等待5秒鍾后,您將取消線程,這就是線程運行5秒鍾的原因。

附帶說明一下,我不鼓勵您使用異步取消來終止線程,因為您不知道線程終止時線程分配的資源狀態。 我建議您找到另一種與線程通信並優雅終止它的方法(例如,使用條件變量)。

這是我的輸出:

thread_function is running
Thread is still running (0)...
Thread is still running (1)...
Thread is still running (2)...
Thread is still running (3)...
Thread is still running (4)...
Canceling thread...
Waiting for thread to finish...

在完成sleep(5)之后,它終止了另一個線程。 這一切對我來說都很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM