简体   繁体   中英

Fire-and-forget std::thread objects cleaning themselves up

When implementing a service, etc, there may be a need for fire-and-forget functionality where one creates a thread and leaves it to its own devices. However, one needs to keep the std::thread object around somewhere to prevent it going out of scope, but when the thread completes there is no neat delete this support, and even if there was, that's going to be a problem for non-pointer allocations. Similarly, higher-level libraries may have Timer objects, where a one-shot timer may be fired off but needs to be cleaned up when done.

One can perhaps keep a collection of std::thread and Timer objects, and every so often go through the list and delete the finished objects, but that seems bothersome. Is there some useful idiom for managing these kinds of temporaries?

My immediate solution has been to use a combination of std::mutex and std::atomic to get my service to return BUSY so I only ever have one thread around, but that feels like a Code Smell

This is what std::thread::detach() is for -- if you want the thread to be "fire and forget", then you call detach on it after creating it. This causes the std:thread object to no longer refer to the actual thread of execution, so you can destroy the std::thread and is has no effect on the execution.

In case of a lot fire-and-forget functionality you may consider using Thread Pool . Creating and destroying of threads have overheads, and a lot of it may eat your RAM in RT. Thread Pool fire up for you X threads ahead for you, that will manage every "fire-and-forget" thread for you.

A simple Thread Pool that solve the problem for me .

std::mutex isn't related to managing threads' resources, it's related to synchronize threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM