在X时间之后执行另一个函数的函数中的线程的问题 [英] Trouble with threads in a function to exec another function after X time
问题描述
我试图创建此函数为了执行另一个函数后X时间:
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);
我已经做了一个Thread封装和一个时间封装(对象Thread和Time)。
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 ;
如何正确删除Thread对象,而不会阻止执行的其余部分,也不冒风险
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!
推荐答案
使用 std :: thread
和 lambdas ,你可以这样做:
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.
这篇关于在X时间之后执行另一个函数的函数中的线程的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!