C++ 异步 async future 等

async 和 future

这个和 C# 的 Task 有点像。

#include <iostream>
#include <string>
#include <memory>
#include <future>
#include <thread>

using namespace std;

int calculate()
{
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return 42;
}

class Dog
{
public:
    int wangWang()
    {
        std::this_thread::sleep_for(std::chrono::seconds(3));
        return 23;
    }
};

int main()
{
    std::future<int> res = std::async(std::launch::async, calculate);
    int result = res.get(); // 这里会等待完成  如果想要非阻塞,可以用 _Is_ready() 先判断是否完成
    cout << result << '\n';
    Dog dog;
    res = std::async(std::launch::async, &Dog::wangWang, &dog); // 成员函数
    int dog_result = res.get();
    cout << dog_result << '\n';

    return EXIT_SUCCESS;
}

输出:

42
23

std::packaged_task

#include <iostream>
#include <memory>
#include <future>
using namespace std;

int calculate(int x, int y)
{
    return x + y;
}

class Dog
{
public:
    int calculate(int x, int y)
    {
        return x + y;
    }
};

int main()
{
    // 直接绑定函数
    std::packaged_task<int(int, int)> task(calculate);
    std::future<int> f_result = task.get_future();
    std::thread t(std::move(task), 100, 200);
    t.join();
    int result = f_result.get();
    cout << result << '\n';

    // bind 类成员函数 可调用对象
    Dog dog;
    std::function<int(int, int)> func = 
        std::bind(&Dog::calculate, &dog, std::placeholders::_1, std::placeholders::_2);
    std::packaged_task<int(int, int)> task_1(func);
    std::future<int> f_result_1 = task_1.get_future();
    std::thread t_1(std::move(task_1), 10, 20);
    t_1.join();
    int result_1 = f_result_1.get();
    cout << result_1 << '\n';

    system("pause");
    return EXIT_SUCCESS;
}

输出:

300
30

promise

能够在某个线程中给它赋值,然后我们可以在其他线程中,把这个取值出来用;

#include <future>
#include <iostream>
int main()
{
    std::promise<int> p;
    std::future<int> f = p.get_future();

    std::thread t([&p]()
        {
            p.set_value(42);
        });
    t.join();

    int result = f.get();
    std::cout << result << std::endl; // 输出42

    system("pause");
    return EXIT_SUCCESS;
}




参考:http://www.seestudy.cn/?list_9/43.html

posted @   double64  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-09-22 C# 去掉字符串多余空格
2021-09-22 C# 统计字符出现次数
2021-09-22 C# 冒泡排序
2021-09-22 C# Math.Round()四舍五入
2021-09-22 C# 交换两个变量值
2021-09-22 英语|play
2021-09-22 C#.Net XML
点击右上角即可分享
微信分享提示