views:

457

answers:

4

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.

+15  A: 

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.

Will
+1  A: 

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

Douglas Leeder
A: 

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.

pjc50
A: 
Neeraj
you interrupted the sleep, not killed it
Will