我试图从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);
}
答案 0 :(得分:2)
等待5秒后你正在取消线程,这就是你的线程运行5秒的原因。
另一方面,我不鼓励您使用异步取消来终止线程,因为您不知道线程终止时分配的资源的状态。 我建议你找到另一种与你的线程进行通信的方法并优雅地终止它(例如使用条件变量)。
答案 1 :(得分:0)
这是我的输出:
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...
在完成睡眠(5)之后,它终止了另一个线程。这对我来说都很好。