c++11之std::async 和std::thread 的区别

c++11之std::async 和std::thread 的区别

std::async和std::thread都是C++11中提供的线程库,它们都可以用于创建新线程。它们的主要区别在于:

  1. std::async有时候并不创建新线程,而是使用线程池中的线程来执行任务,这取决于实现。而std::thread总是创建新线程。
  2. std::async返回一个std::future对象,可以用来获取异步任务的结果。而std::thread没有返回值,需要通过其他方式来获取线程执行的结果。
  3. std::async可以指定任务的执行策略,例如std::launch::async表示一定要创建新线程执行任务,std::launch::deferred表示可以不创建新线程,等到调用std::future的get()方法时再执行任务。而std::thread没有这样的选项。
#include <iostream>
#include <future>
#include <thread>

int task()
{
    std::cout << "Task is running in thread " << std::this_thread::get_id() << std::endl;
    return 42;
}

int main()
{
    // 使用std::async创建异步任务
    std::future<int> f1 = std::async(std::launch::async, task);
    std::cout << "Async task has been started." << std::endl;

    // 使用std::thread创建新线程
    std::thread t(task);
    std::cout << "Thread has been started." << std::endl;

    // 等待异步任务完成并获取结果
    int result1 = f1.get();
    std::cout << "Async task has been finished with result " << result1 << std::endl;

    // 等待线程完成并退出
    t.join();
    std::cout << "Thread has been finished." << std::endl;

    return 0;
}

更直观的看一下std::launch::async 与 ,std::launch::deferred

#include <iostream>
#include <future>

int main() {
    auto f1 = std::async(std::launch::deferred, []() {
        std::cout << "This is a deferred async task." << std::endl;
        return 1;
        });
    auto f2 = std::async(std::launch::async, []() {
        std::cout << "This is a async task." << std::endl;
        return 2;
        });
    std::cout << "Waiting..." << std::endl;
    std::cout << f1.get() << std::endl;
    std::cout << f2.get() << std::endl;
    return 0;
}
  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奥特神龟3.1.4

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值