简体   繁体   English

pthread_cancel不会取消线程— C ++

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

I'm trying to cancel a thread from main. 我正在尝试从main取消线程。 It does not cancel immediately but takes 4seconds approximately. 它不会立即取消,但大约需要4秒钟。 It should because I've set its cancel type to asynchronous from the default (deferred). 这应该是因为我已将其取消类型设置为与默认值(延迟)异步。 Why? 为什么?

#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);
}

You are cancelling the thread after waiting for 5 seconds, which is why your thread runs for 5 seconds. 等待5秒钟后,您将取消线程,这就是线程运行5秒钟的原因。

On a side note, I discourage you from terminating threads with asynchronous cancel, because you don't know the state of the resources allocated by the thread when it terminates. 附带说明一下,我不鼓励您使用异步取消来终止线程,因为您不知道线程终止时线程分配的资源状态。 I suggest you find another way to communicate with your thread and terminate it gracefully (using a condition variable for instance). 我建议您找到另一种与线程通信并优雅终止它的方法(例如,使用条件变量)。

Here is my output: 这是我的输出:

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...

After it's done with the sleep(5) it terminates the other thread. 在完成sleep(5)之后,它终止了另一个线程。 This all looks fine for me. 这一切对我来说都很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM