当我用C ++杀死一个pThread时,堆栈上的对象的析构函数会被调用吗?

时间:2010-01-29 15:51:04

标签: c++ destructor pthreads

我正在编写一个多线程C ++程序。我计划杀死线程。但是,我也在使用重新计算的GC。我想知道当一个线程被杀死时堆栈分配的对象是否会被破坏。

4 个答案:

答案 0 :(得分:15)

当你“杀死”一个帖子时,堆栈不会展开。

杀死线程不是一种强大的操作方式 - 它们打开的资源(如文件)在进程关闭之前保持打开状态。此外,如果他们在您关闭它们时保持打开任何锁定,锁定可能会保持锁定状态。请记住,您可能会调用许多您无法控制的平台代码,而且您无法始终看到这些内容。

关闭线程的优雅健壮的方法是中断它 - 通常它会轮询以查看它是否被告知定期关闭,或者它正在运行消息循环并且你发送一个退出消息。

答案 1 :(得分:1)

我怀疑它--pthread是一个纯粹的C api,所以我怀疑它是否有任何机制来解开线程的堆栈。

答案 2 :(得分:0)

这样做并不标准化。似乎有些实现有,有些却没有。

如果可以,应该避免使用pthread_cancel();它实际上并没有停止线程,直到它到达取消点,这通常是任何其他pthread_ *调用。特别是,在许多平台上,取消不会中断阻塞读取。

答案 3 :(得分:0)


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

虽然与上述观点不一致,但以下代码输出

testing pkill
In the thread
constructor called
sleep..
destructor called
相关问题