Trouble with threads in a function to exec another function after X time

别来无恙 提交于 2020-01-24 01:13:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!