美文网首页
C++ 的 std::promise 和 std::future

C++ 的 std::promise 和 std::future

作者: JSTZ | 来源:发表于2020-05-02 08:57 被阅读0次

介绍

编写多线程应用时,无法避免的要进行线程间数据同步/通信。std::promisestd::future 是 C++ 进行单向数据传递的一种方式。std::promise 是数据的输入端,std::future 是数据的输出端。

用法

使用时,从 std::promiseget_future 得到 std::future,再从 std::future 中得到在 std::promise 端写入的值。如果在从 std::future 获取值时,std::promise 并未写入,那么 std::future 所在的线程将阻塞。

代码

主线程等待另一个线程的数据:

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

int main(int argc, char * argv[])
{
    using namespace std::literals;

    auto promise = std::promise<int>();

    auto t1 = std::thread([&promise]
    {
        std::cout << "thread running\n";

        // 模拟耗时操作
        std::this_thread::sleep_for(2s);

        // 写入数据,这会唤醒正在等待数据的线程
        promise.set_value(42);

        std::cout << "thread end\n";
    });

    // 获取数据,如果数据还没准备好就会阻塞
    std::cout << promise.get_future().get() << std::endl;

    t1.join();
    return 0;
}

可能的输出:

thread running
thread end
42

其中,第一行顺序是确定的,后面两行的顺序是不确定的。

std::shared_future

std::shared_future 顾名思义就是多个线程共享一个 std::shared_future。可用在一个线程传递数据给多个线程的时候,多个线程在自身的线程空间内通过 std::shared_future 共享一个 future,这是线程安全的。

代码

主线程和线程 2 等待线程 1 的数据:

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

int main(int argc, char * argv[])
{
    using namespace std::literals;

    auto promise = std::promise<int>();

    auto t1 = std::thread([&promise]
    {
        std::cout << "thread 1 running\n";

        // 模拟耗时操作
        std::this_thread::sleep_for(2s);

        // 写入数据,这会唤醒正在等待数据的线程
        promise.set_value(42);

        std::cout << "thread 1 end\n";
    });

    auto shared_future = std::shared_future<int>(promise.get_future());

    auto t2 = std::thread([shared_future]
    {
        std::cout << "thread 2 running\n";

        // 获取数据,如果数据还没准备好就会阻塞
        // 这里使用 std::printf 而不是 std::cout,是为了保证输出在同一行
        std::printf("thread 2: %d\n", shared_future.get());

        std::cout << "thread 2 end\n";
    });

    // 获取数据,如果数据还没准备好就会阻塞
    std::printf("main: %d\n", shared_future.get());

    t1.join();
    t2.join();
    return 0;
}

可能的输出:

thread 1 running
thread 2 running
thread 2: 42
thread 2 end
thread 1 end
main: 42

std::shared_future::get 可以无限次调用,而 std::future::get 仅能调用一次。std::shared_future::get 返回的一定是引用(模板参数是 void 时除外)。

std::packaged_task

前面在使用时都是调用 std::promise::set_value 来写入值,有时我们可能想将一个函数的返回值写入。当然,我们可以先调用这个函数得到值再调用 std::promise::set_value,但标准库提供了 std::packaged_task 来代替这种做法。

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

int main(int argc, char * argv[])
{
    using namespace std::literals;

    auto && task = std::packaged_task<int(void)>([]
    {
        std::cout << "running\n";

        // 模拟这个函数执行时间比较长
        std::this_thread::sleep_for(2s);

        std::cout << "end\n";
        return 42;
    });

    // 提前获取 future,等下 task 会被 std::move,之后就无法使用了
    auto && future = task.get_future();

    auto t1 = std::thread(std::move(task));

    std::cout << future.get() << std::endl;

    t1.join();
    return 0;
}

可能的输出:

running
end
42

std::async

前面都是手动启动一个线程,用启动的线程来计算结果。有时我们只想把这个任务异步运行,不关心它是怎么异步运行的,对于这种需求标准库提供了 std::async

代码

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

int main(int argc, char * argv[])
{
    using namespace std::literals;

    auto future = std::async([]
    {
        std::cout << "running\n";

        // 模拟这个函数执行时间比较长
        std::this_thread::sleep_for(2s);

        std::cout << "end\n";
        return 42;
    });

    std::cout << future.get() << std::endl;

    return 0;
}

可能的输出:

running
end
42

特殊用法——仅能使用一次的条件变量

前面说到用 std::promisestd::future 来传递数据,在传递数据同时使两个线程拥有了一定的时序关系。如果我们仅想同步两个线程,没有数据可以传递,就像条件变量一样,在条件变量满足条件后唤醒等待的线程,将 std::promise 的模板参数指定为 void 即可实现。与条件变量不同的是,这种做法仅可唤醒一次。

代码

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

int main(int argc, char * argv[])
{
    using namespace std::literals;

    auto promise = std::promise<void>();

    auto t1 = std::thread([&promise]
    {
        std::cout << "running\n";

        // 模拟这个函数执行时间比较长
        std::this_thread::sleep_for(2s);

        // 唤醒正在等待数据的线程
        promise.set_value();

        std::cout << "end\n";
    });

    std::cout << "before\n";
    // 等待条件触发
    promise.get_future().get();
    std::cout << "after\n";

    t1.join();
    return 0;
}

可能的输出:

before
running
end
after

有关 std::async 返回 std::future 的坑

先看一个例子:

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

int main(int argc, char * argv[])
{
    using namespace std::literals;

    std::cout << "1\n";

    {
        std::async([]
        {
            std::cout << "2\n";

            // 模拟这个函数执行时间比较长
            std::this_thread::sleep_for(2s);

            std::cout << "3\n";

            return 42;
        });
    }

    std::cout << "4\n";

    return 0;
}

这个代码的输出是什么?
因为 std::async 是异步执行,不会阻塞调用者线程。因此结果可能是 1243,也可能是 1423,这取决与异步任务和调用者线程先运行。
实际上一定是 1234,因为 std::async 的返回值在析构时会等待 std::async 运行完成。因此如果将任务放到 std::async 中运行,却没有妥善处理好它的返回值,可能就会和初衷不符。

参考

  1. 标准库头文件 <future>

相关文章

网友评论

      本文标题:C++ 的 std::promise 和 std::future

      本文链接:https://www.haomeiwen.com/subject/wahhghtx.html