繁体   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