C++中thread.join()函数是指等待某一个线程结束,它有两个重载函数:
void join(); templatebool join(const std::chrono::duration & timeout_duration);
用法
第一个重载函数void join()用于等待线程结束,它会一直阻塞,直到线程结束,才会返回。第二个重载函数bool join(const std::chrono::duration
使用示例
#include#include #include void func() { std::cout << "func thread start" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); std::cout << "func thread end" << std::endl; } int main() { std::thread t(func); t.join(); std::cout << "main thread end" << std::endl; return 0; }
上面的示例中,主线程创建了一个新线程t,并使用thread.join()函数等待t线程结束,这样主线程才会继续执行。
注意事项
- 不要对同一个线程调用多次thread.join()函数,因为只有第一次调用才有效,多次调用会导致程序异常。
- 不要对一个已经结束的线程调用thread.join()函数,因为会导致程序异常。
- 线程调用thread.join()函数后,会一直阻塞,直到线程结束,才会返回,应该避免在主线程中使用该函数,以免影响程序的性能。