C++ 异步 async future 等

一万年太久 / 2024-09-22 / 原文

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(); // 这里会等待完成
    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