Let's assume situation that we have two functions:
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});
}
}
and I want to start them in different threads but whether they are started is dependent on some condition, so for example execution of them is just like below:
bool c1 {true};
bool c2 {true};
if (c1) {
std::thread th1 {&foo1};
th1.join ();
}
if (c2) {
std::thread th2 {&foo2};
th2.join ();
}
I know that here in this situation only foo1() will be invoked and foo2() never.
My first thought was to use unique_ptr like this:
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 ();
}
My second thought was to change design a little bit to run threads always, but if condition is false, exit function, so take a look at the code below:
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 ();
I know that asking which one is better is not always good question, but could you suggest me good (and maybe better than those presented) solution to handle situation when at least two threads are starting from different scopes and all of them have to be joined?
vector) and then join all the threads in the container with a loop?