关于c++:C并发与多线程-11stdatomic叙谈stdlaunchstdasync-深入

2次阅读

共计 2098 个字符,预计需要花费 6 分钟才能阅读完成。

std::atomic 叙谈

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

专用的根本数据类型:

char
signed char
unsigned char
short
unsigned short
int
unsigned int
long
unsigned long
long long
unsigned long long
char16_t
char32_t
wchar_t
extended integral types (if any)

附加的成员函数:

atomic::fetch_add
atomic::fetch_sub
atomic::fetch_and
atomic::fetch_or
atomic::fetch_xor
atomic::operator++
atomic::operator--
operator (comp. assign.)
  • 对于 bool 实例化,仅反对惯例原子操作。请留神,大多数 c-style 原子类型都是这些专门化的别名(或这些专门化继承的基类的别名)
  • 原子操作还局部专用于指针类型,具备一下附加成员函数:
atomic::fetch_add
atomic::fetch_sub
atomic::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 1
async_func begin 2
async_func end
1
main 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 1
std::future_status::deferred
async_func begin 1
async_func end
1
main 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);
正文完
 0