[英]how can i separately create and launch my threads
我想要做的是創建一些線程並將其推入向量中,以便在進行某些檢查后啟動它們。
所以在這里我主要想創建如下主題
int main()
{
Pont pont;
for (int k = 0; k <= 20; k++) {
std::thread th(crossBridge);
pont.threadsW.push_back(std::move(th));
}
pont.init();
return 0;
}
並在此處啟動主題:
void WestToEast()
{
cout << "préparation du trafic vers l'est \n";
while (true) {
std::unique_lock<std::mutex> lock(mut);
while (!notified2) {
cond.wait(lock);
}
while (!threadsE.empty() && j < 10) {
j++;
""
" i want to launch theme here "
""
}
j = 0;
notified1 = true;
notified2 = false;
}
}
每個建議都會受到贊賞,以及一旦啟動並從引導程序中刪除后如何加入主題
ps:我剛剛發布了代碼的相關部分
您可以使用默認構造的(空)線程對象填充向量。
for (int k = 0; k<=20; k++)
pont.threadsW.push_back({}); // populate vector with empty thread objects
完成檢查后,將每個矢量對象與一個線程函數相關聯。
for (auto& th : pont.threadsW)
th = thread(crossBridge);
您並不是真正在創建線程並推遲它,直到啟動它為止。而是使用空線程對象填充該向量。 一旦將新線程移到矢量線程對象中,就會創建實際線程並開始運行。
完成后,在每個線程對象上調用join()
。
for (auto& th : pont.threadsW)
th.join();
如果在執行啟動前檢查時線程功能需要處於運行狀態,則需要額外的同步,其中每個線程都在等待全清除信號后才能繼續運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.