简体   繁体   English

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

[英]When I kill a pThread in C++, do destructors of objects on stacks get called?

I'm writing a multi-threaded C++ program. 我正在编写一个多线程C ++程序。 I plan on killing threads. 我计划杀死线程。 However, I am also using a ref-counted GC. 但是,我也在使用重新计算的GC。 I'm wondering if stack allocated objects get destructed when a thread gets killed. 我想知道当线程被杀死时堆栈分配的对象是否被破坏。

The stack does not unwind when you 'kill' a thread. 当你“杀死”一个线程时,堆栈不会展开。

Killing threads is not a robust way to operate - resources they have open, such as files, remain open until the process closes. 杀死线程并不是一种强大的操作方式 - 它们打开的资源(例如文件)在进程关闭之前保持打开状态。 Furthermore, if they hold open any locks at the time you close them, the lock likely remains locked. 此外,如果他们在您关闭它们时保持打开任何锁定,则锁定可能会保持锁定状态。 Remember, you are likely calling a lot of platform code you do not control and you can't always see these things. 请记住,您可能会调用许多您无法控制的平台代码,并且您无法始终看到这些内容。

The graceful robust way to close a thread is to interrupt it - typically it will poll to see if it's been told to close down periodically, or it's running a message loop and you send it a quit message. 关闭线程的优雅健壮的方法是中断它 - 通常它会轮询以查看它是否被告知定期关闭,或者它正在运行消息循环并且您发送一个退出消息。

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

It's not standardised to do this. 这样做并不标准化。 It appears that some implementations do and some don't. 有些实现似乎有些实现,有些则没有。

pthread_cancel() really should be avoided, if you can; pthread_cancel()确实应该避免,如果可以的话; it doesn't actually stop the thread until it hits a cancellation point, which is usually any other pthread_* call. 它实际上并没有停止线程,直到它到达取消点,这通常是任何其他pthread_ *调用。 In particular, on lots of platforms a cancel won't interrupt a blocking read. 特别是,在许多平台上,取消不会中断阻塞读取。


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

Although not coinciding with the views above, the following code outputs 虽然与上面的视图不一致,但以下代码输出

testing pkill
In the thread
constructor called
sleep..
destructor called

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

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