Home > Mobile >  C 11 delay the execution of thread
C 11 delay the execution of thread

Time:05-18

I'd like to crate some threads (with c 11) and collect them in a 'vector'. Then I'd like to fire them up, not immediately upon construction of the associated thread object, but after specified time. And this is my problem, how can I delay the execution of thread?

It is possible to do something like that? I appreciate any hints.

CodePudding user response:

I'd like to crate some threads (with c 11) and collect them in a 'vector'. Then I'd like to fire them up, not immediately upon construction of the associated thread object

You can default construct the std::thread objects:

std::vector<std::thread> threads(some_number);

but after specified time

You can sleep for some time:

std::this_thread::sleep_for(some_time);

Once you're ready to start the execution, create a thread with a function and assign the ones in the vector:

threads[i] = std::thread(some_callable);

That said, creating the empty std::thread objects doesn't necessarily make a lot of sense since you could easily delay creating them until you actually want to execute something.

This approach does make sense when you want to use a constant length array of threads instead of a vector.

CodePudding user response:

Make a vector of std::unique_ptr<std::thread> and only construct them when you want to start them.

Typically:

std::vector<std::unique_ptr<std::thread>> ths;
// When you want to start the thread.
ths.push_back(new std::thread(...what you need here...));

CodePudding user response:

try to call std::this_thread::sleep_for(std::chrono::seconds(1));

  • Related