On Thu, 2020-03-12, Paavo Helde wrote:
> On 12.03.2020 10:41, Frederick Gotham wrote:
>>
>> According to the C++11 Standard, if you create an object of type
>> "std::thread" and start it running, then you must either 'join' or
>> 'detach' before the destructor of the "std::thread" object is
>> called, otherwise "std::terminate" gets called.
>>
>> Are there any pitfalls to doing the following?
>>
>> class Safe_Thread : public std::thread {
>> public:
>>
>> ~Safe_Thread(void)
>> {
>> std::thread::detach();
>> }
>> };
>>
>> My aim here is to have a thread class that behaves exactly like
>> "std::thread" (or indeed boost::thread) but which doesn't call
>> std::terminate if you don't 'join' or 'detach'.
>
> Your aim is understandable, but not very wise. A detached thread cannot
> be joined, meaning that your program is basically not able to guarantee
> a clean shutdown any more. Failing to join the threads properly is just
> sloppy programming.
And an extremely common flaw.
My gut feeling for threads is, you need to design thread lifetimes as
carefully as process lifetimes (for forked processes), and a worker
thread should probably accept a special work request that says "please
exit".
(But that gut feeling is just based on experience dealing with bad
designs. I avoid threads myself.)
> If you still insist on having detached threads, I suggest to use _exit()
> for terminating the program, this will kill it on spot without any
> cleanup of global statics etc, and so it should avoid any errors in the
> still running threads.
How about std::quick_exit()?
/Jorgen
--
// Jorgen Grahn <grahn@ Oo o. . .
\X/
snipabacken.se> O o .