try to understand this example code

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();


And here is the whole code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template <class callable, class... arguments>
void wait(int after, bool async, callable&& f, arguments&&... args)
{
	std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));

	if (async)
	{
		std::thread([after, task]() {
			std::this_thread::sleep_for(std::chrono::milliseconds(after));
			task();
		}).detach();
	}
	else
	{
		std::this_thread::sleep_for(std::chrono::milliseconds(after));
		task();
	}
}


Furthermore, is there any way to kill that async thread before "sleep_for" finishes?
[after, task]() { std::this_thread::sleep_for(std::chrono::milliseconds(after)); task(); } is a lamda function.

It takes after and task as parameters by value from the enclosing scope. std::thread runs the lamda function asynchronously.

detach() is called as we don't need to join to it.
bonho wrote:
why does it call detach?
kbw wrote:
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?

No.
Last edited on
Topic archived. No new replies allowed.