0

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 Answers1

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Wont this block the main execution of the program? –  May 15 '13 at 11:33
  • 1
    @Mayerz No, it "detaches" the new thread to run completely independent of the creating thread. You don't even have to join the thread (nor should you). – Some programmer dude May 15 '13 at 11:35
  • Ok so after calling your code, all memory will be freed automatically? –  May 15 '13 at 11:37
  • 1
    @Mayerz All memory regarding the thread itself anyway. Any memory you allocate _in_ the thread you have to free yourself of course. – Some programmer dude May 15 '13 at 11:40
  • Ok for your previous response. I am still a but confused by your syntax, "[=]()". It works, but i dont understand the [=] thing :). –  May 15 '13 at 11:41
  • 1
    @Mayerz It's part of the lambda capture, and means "capture everything by value". – Some programmer dude May 15 '13 at 11:46
  • Ok thanks for edit, it's a new feature for me, I am gonna check it. Thanks for the effective and fast answer! –  May 15 '13 at 11:49