std::thread 成员函数
时间: 2023-11-07 16:50:27 浏览: 94
`std::thread` 是 C++11 中引入的多线程库,它提供了一种方便的方式来创建和管理线程。
`std::thread` 类的成员函数包括:
1. `thread()`:默认构造函数,创建一个空的线程对象。
2. `thread(Args&&... args)`:构造函数,创建一个新的线程对象,并传递给定参数 args 给线程函数。
3. `~thread()`:析构函数,销毁线程对象。
4. `operator=()`:赋值运算符,用于将一个线程对象赋值给另一个线程对象。
5. `join()`:阻塞调用线程,直到当前线程完成执行。
6. `detach()`:分离线程,允许线程独立执行。
7. `swap()`:交换两个线程对象。
8. `get_id()`:返回线程对象的唯一标识符。
9. `native_handle()`:返回底层操作系统的原生句柄。
这些成员函数可以帮助你创建、管理和操作线程对象。你可以根据需要选择适当的成员函数来使用 `std::thread` 类。
相关问题
std::thread 成员函数
`std::thread`是C++标准库中的一个线程处理类,用于创建和管理线程。它的一些主要成员函数包括:
1. **ctor/dtor (构造/析构)**:
- `std::thread(const std::function<void()>& func)` 或 `std::thread(std::thread::id id, void(*)()`:构造函数接收一个可调用对象(如函数指针、lambda表达式)作为线程执行的目标。
- `~thread()`:析构函数,在线程结束时自动调用,清理资源。
2. **start()**:
- `void start()`:开始执行线程。如果线程已经启动,这将抛出异常。
3. **join()**:
- `void join()`:等待线程完成。调用者会阻塞直到线程执行完毕。
- `bool join_for(time_t timeout)`:带超时的版本,可以设置最大等待时间。
4. **detach()**:
- `void detach()`:从当前线程分离该线程,使其独立运行。不再关心线程是否终止。
5. **id() const**:
- `thread::id id()`:返回线程ID,表示线程的唯一标识符。
6. **interrupt()** 和 **try_join_for()**:
- `void interrupt()`:中断正在执行的线程。
- `bool try_join_for(time_t timeout)`:尝试在一个指定的时间内等待线程结束,如果没有完成则返回false。
7. **native_handle() const**:
- `native_thread_t native_handle()`:提供底层操作系统线程的原始句柄,用于更底层的操作。
8. **get_id() const**:
- `const thread::id& get_id()`:获取线程ID的引用。
以上是一些主要的成员函数,使用它们可以创建、控制和操作C++11及更高版本中的线程。
c++ std::thread 成员函数
### C++ `std::thread` 成员函数及其用法
#### 构造函数
构造一个新的线程对象,该线程不会关联任何执行线程。如果提供了可调用目标,则启动新线程并立即开始执行给定的目标。
```cpp
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
```
此模板构造函数接受一个可调用的对象以及任意数量的参数,并将这些参数转发给可调用对象以在线程中执行[^3]。
#### join 函数
等待线程完成其操作。这会阻塞当前线程直到被join的线程结束运行。
```cpp
void join();
```
只有当线程已经启动(`joinable`)时才能调用此方法;否则程序行为未定义。成功返回后,线程不再处于加入状态(joinable)[^4]。
#### detach 函数
分离线程使其独立于主线程继续执行,即允许子线程在其生命周期内异步终止而无需显式地由另一个线程通过`join()`等待它。
```cpp
void detach();
```
一旦调用了detach(), 就不能再对该线程使用`join()`, 同样也不能再次调用`detach()`.
#### swap 函数
交换两个线程的身份,包括它们各自的线程ID和其他属性。
```cpp
void swap(thread& other);
```
互换两个线程的状态,使得原线程持有其他线程的资源,反之亦然。
#### native_handle 函数
获取平台特定的句柄,以便可以直接访问底层操作系统API来进行更细粒度的操作。
```cpp
native_handle_type native_handle();
```
提供对底层实现细节的访问权限,通常仅限高级用途或调试目的。
#### get_id 函数
获得与此`std::thread`实例相关联的独特标识符。
```cpp
id get_id() const;
```
即使对于从未关联过实际OS级别的线程的默认构造对象也会返回唯一的ID值。
#### hardware_concurrency 函数
估计硬件支持的最大并发线程数。
```cpp
static unsigned int hardware_concurrency() noexcept;
```
静态成员函数,用来估算系统上可用的核心数目,有助于决定应用程序应该创建多少个工作线程来充分利用多核处理器的能力。
#### joinable 函数
判断线程是否正在运行且尚未被连接(joined)或者脱离(detached).
```cpp
bool joinable() const;
```
如果线程既不是已销毁也不是已被分离则返回true,意味着它可以安全地被`join()`或`detach()`处理。
阅读全文
相关推荐
















