C++ 多线程 std::thread::join

C++ 多线程 std::thread::join

  • [1. `std::thread::join`](#1. std::thread::join)
  • [2. Parameters](#2. Parameters)
  • [3. Return value](#3. Return value)
  • [4. Examples](#4. Examples)
  • [5. Data races (数据竞争)](#5. Data races (数据竞争))
  • [6. Exception safety (异常安全性)](#6. Exception safety (异常安全性))
  • References

https://cplusplus.com/reference/thread/thread/join/

public member function

1. std::thread::join

void join();

The function returns when the thread execution has completed.

阻塞当前线程,直到线程完成其执行。主线程调用 std::thread::join 会阻塞等待子线程完成,确保所有资源正确释放,避免进程退出时资源泄露或段错误。

This synchronizes the moment this function returns with the completion of all the operations in the thread: This blocks the execution of the thread that calls this function until the function called on construction returns (if it hasn't yet).

这会将该函数返回的时刻与线程中所有操作的完成同步:这会阻止调用该函数的线程的执行,直到构造时调用的函数返回 (如果尚未返回)。

After a call to this function, the thread object becomes non-joinable (std::thread::joinable) and can be destroyed (std::thread::~thread) safely.

2. Parameters

none

3. Return value

none

4. Examples

复制代码
#include <iostream> 
#include <thread> 
#include <chrono> 

void pause_thread(int n) {
	std::this_thread::sleep_for(std::chrono::seconds(n));
	std::cout << "pause of " << n << " seconds ended" << std::endl;
}

int main() {
	std::cout << "Spawning 3 threads..." << std::endl;
	std::thread t1(pause_thread, 1);
	std::thread t2(pause_thread, 2);
	std::thread t3(pause_thread, 3);
	std::cout << "Done spawning threads. Now waiting for them to join:" << std::endl;

	t1.join();
	t2.join();
	t3.join();
	std::cout << "All threads joined!" << std::endl;

	return 0;
}

Spawning 3 threads...
Done spawning threads. Now waiting for them to join:
pause of 1 seconds ended
pause of 2 seconds ended
pause of 3 seconds ended
All threads joined!
请按任意键继续. . .

5. Data races (数据竞争)

The object is modified.

Note that any operations on the thread object itself are not synchronized (unlike the operations within the thread it represents).

6. Exception safety (异常安全性)

Basic guarantee: if an exception is thrown by this member function, the thread object is left in a valid state.

If the call fails, a std::system_error exception is thrown:

exception type error condition description
std::system_error errc::invalid_argument The thread object is not joinable
std::system_error errc::no_such_process The thread object is not valid
std::system_error errc::resource_deadlock_would_occur The current thread is the same as the thread attempted to join, or A deadlock was detected (implementations may detect certain cases of deadlock).

Note that if the thread represented by the object terminates with an uncaught exception, this cannot be caught by the current thread, and std::terminate is automatically called.

References

1\] Yongqiang Cheng, \[2\] `std::thread::join`,