std::atomic 叙谈

  • 原子类模板齐全专用于根本整数类型(bool除外),以及 <cstdint> 中 typedef 所需的任何扩大整数类型。

专用的根本数据类型:

charsigned charunsigned charshortunsigned shortintunsigned intlongunsigned longlong longunsigned long longchar16_tchar32_twchar_textended integral types (if any)

附加的成员函数:

atomic::fetch_addatomic::fetch_subatomic::fetch_andatomic::fetch_oratomic::fetch_xoratomic::operator++atomic::operator--operator (comp. assign.)
  • 对于 bool 实例化,仅反对惯例原子操作。请留神,大多数 c-style 原子类型都是这些专门化的别名(或这些专门化继承的基类的别名)
  • 原子操作还局部专用于指针类型,具备一下附加成员函数:
atomic::fetch_addatomic::fetch_subatomic::operator++atomic::operator--operator (comp. assign.)

std::launch(std::async) 深刻了解

std::async

enum class launch : /* unspecified */ {    async =    /* unspecified */,    deferred = /* unspecified */,    /* implementation-defined */};
  • 此枚举类型用于定义 aync 异步调用中的启动策略。

launch::async

  • 入口函数由新线程异步调用,并将其返回其与共享状态的拜访点同步。
#include <iostream>#include <future>#include <thread>using namespace std;bool async_func () {    cout << "async_func begin " << std::this_thread::get_id() << endl;    cout << "async_func end" << endl;    return true;}int main (){  cout << "main begin " << std::this_thread::get_id() << endl;  std::future<bool> fut = std::async (launch::async, async_func);   // 创立新线程并调用线程入口函数  cout << fut.get() << endl;  cout << "main end" << endl;  return 0;}

输入:

main begin 1async_func begin 2async_func end1main end

launch::deferred

  • 入口函数提早调用。
  • 在调用线程拜访 future 对象的 wait, get 函数时,入口函数才被调用。
  • 同时未创立新线程,入口函数在 future 对象被调用的线程中执行。
#include <iostream>#include <future>#include <thread>using namespace std;bool async_func () {    cout << "async_func begin " << std::this_thread::get_id() << endl;    cout << "async_func end" << endl;    return true;}int main (){  cout << "main begin " << std::this_thread::get_id() << endl;  std::future<bool> fut = std::async (launch::deferred, async_func);  if (fut.wait_for(std::chrono::microseconds(0)) == std::future_status::deferred)   // 查看是否是 launch::deferred   {    cout << "std::future_status::deferred" << endl;  }  cout << fut.get() << endl;    // 入口函数被调用  cout << "main end" << endl;  return 0;}

输入:[留神两处打印的线程id]

main begin 1std::future_status::deferredasync_func begin 1async_func end1main end

launch::async | launch::deferred

  • 根据零碎和库的实现,主动抉择启动策略。
  • 准则次要为是否有足够的系统资源创立线程
  • 这也是未明确指定参数时的默认实现。
std::future<bool> fut = std::async (launch::async|launch::deferred, async_func);==std::future<bool> fut = std::async (async_func);