search

Home  >  Q&A  >  body text

c++ - 多线程中的join先后顺序问题

join会阻塞当前线程,但是如下实例的输出:

    thread t1([](){
                this_thread::sleep_for(chrono::milliseconds(500));
                cout<<"t1"<<endl;
            });

    thread t2([](){
                cout<<"t2"<<endl;
            });

    t1.join();
    cout<<"main"<<endl;
    t2.join();

输入先后为什么是:t2 t1 main

编译工具:clang++

迷茫迷茫2804 days ago986

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 11:46:27

    Join blocks the thread that calls the join function. Its purpose is to wait for and confirm the completion of the execution of threads t1 and t2. It cannot guarantee the execution order of multiple threads. Similar to the waitpid function of the process. What can control the order of thread execution is thread mutex and condition

    reply
    0
  • 迷茫

    迷茫2017-04-17 11:46:27

    The function of

    join is to "determine that the thread being joined has ended", and it has nothing to do with the order of thread execution.

    reply
    0
  • Cancelreply