讓我們假設我們有兩個功能的情況:運行C++線程()
void foo1() {
while (true) {
std::cout << "foo1" << std::endl;
std::this_thread::sleep_for (std::chrono::milliseconds {100});
}
}
void foo2() {
while (true) {
std::cout << "foo2" << std::endl;
std::this_thread::sleep_for (std::chrono::milliseconds {100});
}
}
,我要開始他們在不同的線程,但它們是否開始是依賴於某些條件,所以例如他們的執行就像下面:
bool c1 {true};
bool c2 {true};
if (c1) {
std::thread th1 {&foo1};
th1.join();
}
if (c2) {
std::thread th2 {&foo2};
th2.join();
}
我這裏在這種情況下,只知道foo1()
將被調用和foo2()
從來沒有。
我首先想到的是使用unique_ptr
這樣的:
bool c1 {false};
bool c2 {false};
std::unique_ptr<std::thread> pth1 {};
std::unique_ptr<std::thread> pth2 {};
if (c1) {
pth1 = std::unique_ptr<std::thread> {new std::thread {&foo1}};
}
if (c2) {
pth2 = std::unique_ptr<std::thread> {new std::thread {&foo2}};
}
if (pth1) {
pth1->join();
}
if (pth2) {
pth2->join();
}
我的第二個想法是改變一下設計始終運行的線程,但如果條件爲假,退出功能,所以來看看下面的代碼:
void foo1 (bool c) {
if (c) {
while (true) {
std::cout << "foo1" << std::endl;
std::this_thread::sleep_for (std::chrono::milliseconds {100});
}
}
}
void foo2 (bool c) {
if (c) {
while (true) {
std::cout << "foo2" << std::endl;
std::this_thread::sleep_for (std::chrono::milliseconds {100});
}
}
}
bool c1 {true};
bool c2 {true};
std::thread th1 {&foo1, c1};
std::thread th2 {&foo2, c2};
th1.join();
th2.join();
我知道問哪個更好並不總是很好的問題,但你可以建議我好了(也許比呈現更好)解決方案來處理的情況時,至少有兩個線程開始來自不同的sc開放和所有他們必須加入?
爲什麼不把線程保存在一個容器(如'vector')中,然後用循環加入容器中的所有線程? –