代码之家  ›  专栏  ›  技术社区  ›  Alan

将join调用移动到try块内部是否同样安全

  •  0
  • Alan  · 技术社区  · 2 年前

    我对《C++并发》一书中给出的以下代码片段有疑问。我想知道是否有技术原因 t.join() 在try-catch块之后,不要将其放入try块中。

    //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
    }
    

    如您所见,作者已将 t.join() 在点 #2 但我 想知道为什么我们不把它放在里面 try 阻塞本身 ,刚接到电话 do_something_in_current_thread() 我的意思是,把它放在那里有什么技术案例/优势吗 2. 而不是在里面 尝试 我可能不知道这个块,因为我刚刚开始学习多线程。

    作为一个初学者,我想不出有什么好处 2. 而是在try块内。

    请注意,我知道还有 jthread 在本书的后面部分,但我并不是在寻找解决方法。相反,我只问给定的代码。

    2 回复  |  直到 2 年前
        1
  •  2
  •   Ted Lyngmo    2 年前

    为什么不在try block里面

    你可以移动第二个 join() 到 try 阻塞,因为这两条路径都将导致线程连接,就像如果 join() 保存在函数末尾。

    从技术上讲,没有理由偏爱其中一种。

    请注意,在C++20中,可以通过使用自动连接来避免这种情况 std::jthread 相反:

    void f() {
      int some_local_state = 0;
      func my_func(some_local_state);
      std::jthread t(my_func);
      do_something_in_current_thread();
    }
    
        2
  •  -1
  •   Pepijn Kramer    2 年前

    如果你想在投掷或非投掷条件下发生一些事情,你可以使用有作用域的防护装置。一个最小的例子是:

    #include <thread>
    #include <functional>
    
    void do_something_in_current_thread()
    {};
    
    class simple_scope_guard
    {
    public:
        simple_scope_guard(std::function<void> fn) :
            guard{ fn }
        {
        }
    
        ~simple_scope_guard()
        {
            guard();
        }
    private:
        std::function<void> guard;
    };
    
    struct my_func;
    void f()
    {
        int some_local_state = 0;
        std::thread t([] {});
    
    // start a scope to manage the lifetime of the scope guard
        { 
            simple_scope_guard scope_guard{ [&] { t.join(); } };
            do_something_in_current_thread();
            // whether do_something throws or not scope_guard will go out of scope and 
            // call thread.join
        }
    }