I looked for a general way to get a function that does a sync/async "wait x sec and do something" and came across with below. It works perfectly but I'm trying to understand the part when it creates the async thread
what does it mean in ([after, task)] and why does it call detach?
1 2 3
std::thread([after, task]() {
// do its thing with reference to after and task
}).detach();
detach() is called as we don't need to join to it.
To clarify: In the body of the if the thread created is a temporary. The temporary will be immediately destructed at the end of the expression where it is created. If the thread is not detached before this happens, it will be as if join was called on the thread which would mean that the launching thread would wait for the temporary thread to finish. Obviously this would not be an asynchronous call, so detach is necessary to free us from managing the thread object's lifetime.
bonho wrote:
Furthermore, is there any way to kill that async thread before "sleep_for" finishes?