C++并发(C++11)-02 线程管理基础

线程的执行时机

  线程在其对象被创建后立即执行。

等待线程和分离线程

  1. 线程创建后通过调用thread对象的join()或detach()函数决定线程是等待还是分离;
  2. 不能对没有执行线程的thread对象使用join()或detach();
  3. 使用join()或detach()之前应对thread对象进行判断,t.joinable()返回为true时才可使用。

detach()

  detach()用于分离线程,一般在线程被创建后立即调用。其相关资源由系统回收。

join()

  1. join()会等待线程完成(join()后的代码在线程及其相关代码执行完成后才会执行),并回收线程的资源;
  2. 一个线程对象只能被join()一次;
  3. join()的位置要精心挑选,如果在join()之前抛出异常或返回,join()就不会被执行,线程的相关资源就不会被及时回收(进程结束后被操作系统回收)。
#include <iostream>
#include <thread>
using namespace std;

void func(int m) {
  for (size_t i = 0; i < 1000; i++) {
    cout << m++ << endl;
  }
}

int main() {
  int m = 0;
  thread my_thread(func, m);
  throw exception();
  my_thread.join();//不会被执行
  return 0;
}

//
void func(int m) {
  for (size_t i = 0; i < 1000; i++) {
    cout << m++ << endl;
  }
}

int main() {
  int m = 0;
  thread my_thread(func, m);
  try {
    throw exception();
  } catch (const std::exception& e) {
    my_thread.join();  //会被执行
    throw e;
  }
  my_thread.join();  //不会被执行
  return 0;
}

 

线程数量

  std::thread::hardware_concurrency()能获取硬件并发数量,用以辅助确定线程数量。

线程ID

  std::thread对象可通过get_id()获取线程ID;

  可通过std::this_thread::get_id()静态函数获取当前线程ID。

posted @ 2019-09-27 15:46  二杠一  Views(151)  Comments(0Edit  收藏  举报