我正在编写一个多线程C ++程序。我计划杀死线程。但是,我也在使用重新计算的GC。我想知道当线程被杀死时堆栈分配的对象是否被破坏。
我正在编写一个多线程C ++程序。我计划杀死线程。但是,我也在使用重新计算的GC。我想知道当线程被杀死时堆栈分配的对象是否被破坏。
当你“杀死”一个线程时,堆栈不会展开。
杀死线程并不是一种强大的操作方式 - 它们打开的资源(如文件)在进程关闭之前保持打开状态。此外,如果他们在关闭锁时打开任何锁,锁可能会保持锁定状态。请记住,您可能会调用许多您无法控制的平台代码,并且您无法始终看到这些内容。
关闭线程的优雅强大方法是中断它 - 通常它会轮询以查看它是否被告知定期关闭,或者它正在运行消息循环并且您发送一个退出消息。
我怀疑它--pthread是一个纯粹的C api,所以我怀疑它是否有任何机制来解开线程的堆栈。
这样做并不标准化。有些实现似乎有些实现,有些则没有。
如果可以的话,真的应该避免使用pthread_cancel();它实际上并没有停止线程,直到它到达取消点,这通常是任何其他pthread_ *调用。特别是,在许多平台上,取消不会中断阻塞读取。
#include<iostream>
#include<pthread.h>
class obj
{
public:
obj(){printf("constructor called\n");}
~obj(){printf("destructor called\n");}
};
void *runner(void *param)
{
printf("In the thread\n");
obj ob;
puts("sleep..");
sleep(4);
puts("woke up");
pthread_exit(0);
}
int main(int argc,char *argv[])
{
int i,n;
puts("testing pkill");
pthread_attr_t attr;
pthread_t tid;
//create child thread with default attributes
pthread_attr_init(&attr);
pthread_create(&tid,&attr,runner,0);
pthread_cancel(tid);
pthread_join(tid,NULL);//wait till finished
//the parent process outputs value
return 0;
}
虽然与上面的视图不一致,但以下代码输出
测试pkill 在线程中 构造函数调用 睡觉.. 析构函数叫