问题
I am trying to create this function in order to exec another function after X time:
void execAfter(double time, void *(*func)(void *), t_params *params);
I have made an Thread encapsulation and a Time encapsulation (objects Thread and Time).
What I want to do in pseudo code:
Call execAfter
instantiate Thread
call thread->create(*funcToExec, *params, timeToWait)
[inside thread, leaving execAfter]
instanciate Time object
wait for X time
exec funcToExec
delete Time object
[leaving thread, back to execAfter]
delete Thread object <---- probleme is here, see description below.
return ;
How can I delete my Thread object properly, without blocking the rest of the execution nor taking the risk to delete it before required time has elapsed.
I am quite lost, any help appreciated!
回答1:
Using std::thread and lambdas, you could do it something like this:
void execAfter(const int millisecs, std::function<void(void*)> func, void* param)
{
std::thread thread([=](){
std::this_thread::sleep_for(std::chrono::milliseconds(millisecs));
func(param);
});
// Make the new thread "detached" from the parent thread
thread.detach();
}
The "magic" that you are looking for is the detach call.
来源:https://stackoverflow.com/questions/16563739/trouble-with-threads-in-a-function-to-exec-another-function-after-x-time