让我们假设我们有两个功能的情况:运行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')中,然后用循环加入容器中的所有线程? –