我想創建一些執行緒(使用 c 11)并將它們收集在一個“向量”中。然后我想啟動它們,不是在構造關聯執行緒物件時立即啟動,而是在指定時間后啟動。這是我的問題,我怎樣才能延遲執行緒的執行?
有可能做這樣的事情嗎?我很感激任何提示。
uj5u.com熱心網友回復:
我想創建一些執行緒(使用 c 11)并將它們收集在一個“向量”中。然后我想啟動它們,而不是在構造關聯的執行緒物件時立即啟動
您可以默認構造std::thread物件:
std::vector<std::thread> threads(some_number);
但在指定時間之后
你可以睡一段時間:
std::this_thread::sleep_for(some_time);
準備好開始執行后,使用函式創建一個執行緒并分配向量中的函式:
threads[i] = std::thread(some_callable);
也就是說,創建空std::thread物件并不一定很有意義,因為您可以輕松地延遲創建它們,直到您真正想要執行某些東西。
當您想要使用恒定長度的執行緒陣列而不是向量時,這種方法確實有意義。
uj5u.com熱心網友回復:
我的貢獻是為您提供一個簡單的作業代碼,因為@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();
}
uj5u.com熱心網友回復:
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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/479438.html
