线程连接是如何工作的

How does thread join work?

本文关键字:工作 何工作 连接 线程      更新时间:2023-10-16

我发现了一个基于线程的c++ web服务器示例。

我替换了

中的第161行
server_thread.join();

std::cout<<"Before thread joinn";
server_thread.join();
std::cout<<"5 sec delay starting ...n";
this_thread::sleep_for(chrono::seconds(5));
std::cout<<"5 sec delay endedn";

结果明显显示join之后的代码没有运行。

123
{"firstName": "John","lastName": "Smith","age": 25}
John Smith
Before thread join

而在下面的简单示例中,thread_2.join();下面的代码也可以运行。而它不运行最后的std::cout,直到两个线程被释放。.join();背后的逻辑是什么?它暂停当前线程吗?

如果我希望server_thread.join();之后的代码继续与服务器一起运行,正确的解决方案是什么?

main.cpp

#include <boost/thread.hpp>
#include <iostream>
#include <thread>
void task1() { 
    // do stuff
    for(int i=0;i<10;i++)
    {
        std::cout<<"task1 "<<"["<<i<<"]n";
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}
void task2()
{ 
    for(int i=0;i<10;i++)
    {
        std::cout<<"task2 "<<"["<<i<<"]n";
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}
int main ()
{
    using namespace boost; 
    std::thread thread_1 = std::thread(task1);
    std::thread thread_2 = std::thread(task2);
    // do other stuff
    thread_2.join();
    thread_1.join();
    // std::this_thread::sleep_for(std::chrono::seconds(10));
    std::cout<<"end of main functionn";
    return 0;
}

结果:

task1 [0]
task2 [0]
task1 [1]
task2 [1]
task1 [2]
task2 [2]
task1 [task2 [33]
]
task2 [4]
task1 [4]
task2 [5]
task1 [5]
task2 task1 [[66]
]
task2 [task1 [77]
]
task2 task1 [[88]
]
task2 [9]
task1 [9]
end of main function

thread::join等待线程完成。

在你的第一个例子中,server_thread保持或多或少无限期地运行;join的目的是防止main方法过早返回(因为这会杀死服务器线程)。

在第二个示例中,线程只是快速执行任务,然后关闭,因此join很快返回。