Search code examples
c++multithreading

Is it equally safe to move the join call to inside the try block


I have a question/doubt about the following snippet given n the book "C++ concurrency". I want to know is there a technical reason(s) for putting the t.join() after the try catch block instead of putting it inside the try block.

//callable whose defintion is not related to this question
struct my_func; 
void f()
 {
  int some_local_state = 0;
  func my_func(some_local_state);
  std::thread t(my_func);
  try {
    do_something_in_current_thread();
    //can we put/move the t.join() here? instead of having it at point #2
  } catch (...) {
    t.join();
    throw;
  }
  //author put the t.join() here why not inside try block
  t.join(); //#2
}

As you can see, the author has placed the t.join() at point #2. But I want to know why don't we just place it inside the try block itself, just after the call to do_something_in_current_thread(). I mean, are there any technical cases/advantages of placing it at #2 instead of inside the try block that I may not be aware of as I've just started learning multi-threading.

As a beginner I can't think of any case/advantage of having it at #2 instead inside try block.

Note that I know that there is also jthread in the later section of the book but I am not looking for a workaround. Instead I am asking about the given code only.


Solution

  • why not inside try block

    You can move the second join() to the try block since both paths will then lead to joining the thread, just as it will if the join() is kept at the end of the function.

    There's no technical reason to prefer one over the other.

    Note that in C++20, the situation can be avoided by using an auto-joining std::jthread instead:

    void f() {
      int some_local_state = 0;
      func my_func(some_local_state);
      std::jthread t(my_func);
      do_something_in_current_thread();
    }