C++11新特性之线程async

async

在C++中,async 是标准库中的一种异步操作工具,用于启动异步任务。它是C++11引入的一部分,位于头文件 中。std::async 提供了一种轻量级的方式来创建线程或异步任务并获取结果。

定义

std::async 是一个模板函数,定义如下:

template< class Function, class... Args >
std::future<typename std::result_of<Function(Args...)>::type>
async( std::launch policy, Function&& f, Args&&... args );

policy: 指定如何启动任务,有以下选项:
std::launch::async: 强制在新线程中异步执行。
std::launch::deferred: 延迟执行,直到调用 get 或 wait。
std::launch::async | std::launch::deferred(默认): 由实现决定是否创建新线程或延迟执行。
f: 要执行的函数。
args: 函数的参数。

功能与作用

  1. 任务并行: 提高程序的运行效率。
  2. 简化多线程操作: 管理线程及其结果的同步。
  3. 提供线程返回值: 使用 std::future 获取异步任务的返回值。

async参考代码示例

以下代码展示了 std::async 的基本用法:

#include <iostream>
#include <future>
#include <thread>
#include <chrono>

// 一个耗时的任务
int longTask(int duration, const std::string& taskName) {
   
   
    std::cout << "Task " << taskName << " started in thread "
              << std::this_thread::get_id() << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(duration));
    std::cout << "Task " << taskName << " finished." << std::endl;
    return duration * 2;
}

int main() {
   
   
    // 启动异步任务,指定为 std::launch::async 强制使用新线程
    auto future1 = std::async(std::launch::async, longTask, 3, "A");

    // 启动延迟任务(deferred)
    auto future2 = std::async(std::launch::deferred, longTask, 2, "B");

    // 主线程的任务
    std::cout << "Main thread is running in thread "
              << std::this_thread::get_id() << std::endl;

    // 获取结果
    int result1 = future1.get(); // 立即启动并等待完成
    std::cout << "Result of Task A: " << result1 << std::endl;

    int result2 = future2.get(); // 延迟任务在这里执行
    std::cout << "Result of Task B: " << result2 << std::endl;

    return 0;
}

async参考代码输出结果

Main thread is running in thread 140147801564992
Task A started in thread 140147783354112
Task A finished.
Result of Task A: 9
Task B started in thread 140147801564992
Task B finished.
Result of Task B: 4

async参考代码解释

  1. longTask: 一个模拟耗时操作的函数。
  2. std::async 的两种策略:
    std::launch::async: 强制新线程执行任务。
    std::launch::deferred: 延迟任务,只有在调用 get() 或 wait() 时才执行。
  3. std::future:
    用于存储异
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值