C++ Reference 之 Thread Class

C++ 中提供了 Thread(用来表示分别执行的线程的类) 线程类.

在多线程环境中,一个执行的线程是一个能被与其他线程的指令序列并发执行的指令序列,它们共享一个地址空间。
一个初始化过的 thread 对象表示一个有效的执行线程; 这样的线程是 joinable 并且有一个唯一的 thread id。

一个默认构造的(没有被初始化的) thread 对象是 non-joinable , 它的 thread id 与所有 non-joinable 的线程共用。
一个 joinable 线程被 moved 之后或者调用 join 或 detach 之后就变为 non-joinable。

成员类型:

id Thread id(public member type)
native_handle_type Native handle type(public member type)

成员函数

构造函数
析构函数
operator= Move-assign thread(public)
get_id 获取 thread id(public)
joinable 检查线程是否 joinable(public)
join Join thread(public)
detach 分离 thread(public)
swap 交换 thread(public)
native_handle 获得 native handle(public)
hardware_concurrency[static] 检查硬件并发性(public static)

非成员重载函数

swap(thread) 交换 threads (function)

Example

// thread example
#include <iostream>
#include <thread>

void foo() {
  std::cout << "foo" << std::endl;
}

void bar(int x) {
  std::cout << "bar int x" << std::endl;
}

int main() {
  // 创建一个调用 foo 接口的线程。
  std::thread first(foo);
  // 创建一个调用 bar 接口 参数为 int 的线程。
  std::thread second(bar, 0);
  
  std::cout << "main, foo and bar now execute concurrently...\n";
  // 等待线程结束
  first.join();
  second.join();
  std::cout << "foo and bar completed.\n";

  return 0;
}

猜你喜欢

转载自blog.csdn.net/VOlsenBerg/article/details/103542484