c++ 11延迟线程执行



我想创建一些线程(使用c++11)并将它们收集在一个'矢量'中。然后,我希望在指定的时间之后,而不是在相关线程对象构造之后立即启动它们。这就是我的问题,我怎样才能延迟线程的执行?

这样做是可能的吗?谢谢你的提示。

我想创建一些线程(使用c++11)并将它们收集在一个'矢量'中。然后我想启动它们,而不是在相关线程对象

构造完成后立即启动它们。

您可以默认构造std::thread对象:

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

但在指定时间后

你可以睡一会儿:

std::this_thread::sleep_for(some_time);

一旦你准备好开始执行,创建一个带有函数的线程,并在vector中赋值:

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

也就是说,创建空std::thread对象不一定有很大意义,因为您可以很容易地延迟创建它们,直到您真正想要执行某些操作。

当你想使用一个固定长度的线程数组而不是一个vector数组时,这种方法是有意义的。

我的贡献是为您提供一个简单的工作代码,因为@eerorika已经完美地提供了所有的解释。请随意查看代码中的注释

#include <thread>
#include <iostream>
#include <vector>
#include <chrono>
#include <ctime>
/**
* action:
* @param: wait : duration of wating time before launchin an action
*         index: index of the thread
**/
void action(int wait, int index)
{
// compute current time
std::time_t result = std::time(nullptr);
// and display it
std::string mytime(std::asctime(std::localtime(&result)));
// only remove the end of line char from the time
mytime.pop_back();
std::cout << "Time is "<< mytime << " Create thread "<< index << " and wait " << (int) (wait/1000) << " seconds "<< std::endl;
// force the thread to wait for the provided amount of time
std::this_thread::sleep_for(std::chrono::milliseconds(wait));
// re-compute current time
std::time_t result2 = std::time(nullptr);
mytime=std::asctime(std::localtime(&result2));
mytime.pop_back();
// and display it
std::cout << "launch action "<< index << " "<< mytime << " after "<< (int)(wait/1000) << " seconds" << std::endl;
}
int main()
{
// a vector composed of 3 threads
std::vector<std::thread> vecOfThreads(3);
vecOfThreads[0]=std::thread(action,5000, 0);
//sleep 15 ms to give the first thread to display his starting message
std::this_thread::sleep_for(std::chrono::milliseconds(15));
// create a thread and provide its runnable (function) and the two arguments of the function
// and assign it to an element of your vector
vecOfThreads[1]=std::thread(action,10000, 1);
//sleep 15 ms to give the first thread to display his starting message
std::this_thread::sleep_for(std::chrono::milliseconds(15));
vecOfThreads[2]=std::thread(action,15000, 2);
//sleep 15 ms to give the first thread to display his starting message
std::this_thread::sleep_for(std::chrono::milliseconds(15));
//waiting for the end of each thread
vecOfThreads[0].join();
vecOfThreads[1].join();
vecOfThreads[2].join();
}

std::async就是为了这样的目的。

// Enable lazy and asynchronous evaluation of func(x, y) on a new thread.
auto a = std::async(std::launch::deferred | std::launch::async, &func, x, y);
// Do what you need.
// It is time to execute func(x, y), wait_for returns immediately without
// waiting regardless of timeout_duration value.
a.wait_for(0s);
// Do other work you need.
// Get the result, wait for a until it is finished if needed.
auto r = a.get();

最新更新