multithreading - Running C++ threads from different scope using join() -


let's assume situation have 2 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 want start them in different threads whether started dependent on condition, example execution of them 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 here in situation foo1() invoked , foo2() never.

my first thought use unique_ptr 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 change design little bit run threads always, if condition false, exit function, take @ 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 asking 1 better not question, suggest me (and maybe better presented) solution handle situation when @ least 2 threads starting different scopes , of them have joined?

a std::thread object doesn't have represent thread. think simplest is:

    std::thread th1, th2;     if (c1)         th1 = std::thread{&foo1};     if (c2)         th2 = std::thread{&foo2};      if (th1.joinable())         th1.join();     if (th2.joinable())         th2.join(); 

or even:

std::thread maybe_start( void(*f)(), bool c) {     if (c)         return std::thread{f};     else         return {} } void maybe_wait(std::thread& thr) {     if (thr.joinable())         thr.join(); }  ....     std::thread thr1 = maybe_start(&foo1, c1);     std::thread thr2 = maybe_start(&foo2, c2);      maybe_wait(thr1);     maybe_wait(thr2); 

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -