Reputation: 1882
In my c++ class I make a thread and give the pointer this
to the thread. Now somewhere this object is getting deleted. I want the thread to exit after object is deleted.
One method is to use try-catch. Whenever I find an exception I exit the thread. But thats kind of a hack.
Upvotes: 0
Views: 316
Reputation: 52169
Now somewhere this object is getting deleted. I want the thread to exit after object is deleted.
This is completely backwards. What you want to do is to signal the thread to exit somehow and have the thread clean up the object itself. In other words, there has to be some kind of cooperation between the "master" thread and the "worker" thread(s).
This is because the thread itself might want to be able to do something with the object before exiting, and if you delete it then cause the thread to exit, your program will almost certainly die from access violation exceptions.
Consider using boost::thread
, which has built-in support for cooperative thread cancellation. The thread will periodically check when it's time to exit using one of the interruption points, performing any necessary cleanup. That way, the "master" thread doesn't have to deal with deleting the object itself, it can just signal the thread to exit, and it'll take care of itself (assuming you implement this correctly).
Upvotes: 6
Reputation: 308
I would wrap it in a structure containing the this pointer and some kind of flag to report if the object was deleted. This way you at least avoid exception code.
Upvotes: 0