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

寵の児 提交于 2020-01-10 18:44:48

问题


I'm writing a multi-threaded C++ program. I plan on killing threads. However, I am also using a ref-counted GC. I'm wondering if stack allocated objects get destructed when a thread gets killed.


回答1:


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.




回答2:


I doubt it - pthread is a pure C api, so I doubt it would have any mechanism to unwind the stack of the thread.




回答3:


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; it doesn't actually stop the thread until it hits a cancellation point, which is usually any other pthread_* call. In particular, on lots of platforms a cancel won't interrupt a blocking read.




回答4:



#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


来源:https://stackoverflow.com/questions/2163090/when-i-kill-a-pthread-in-c-do-destructors-of-objects-on-stacks-get-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!