开发者

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

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 sta开发者_StackOverflowck 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.


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


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.



#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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜