使用Promise和Future将值从子线程传递到主线程

时间:2018-12-14 10:02:07

标签: c++ multithreading c++11 concurrency

我试图使用future和promise以异步方式将数据从主线程发送到子线程。这是代码。

#include <bits/stdc++.h>
using namespace std;
int sampleFunc(vector<future<int>> &f) {

    int a = f[0].get();
    cout <<"got a from promise 1" << endl;

    int b = f[1].get();
    cout <<"got b from promise 2" << endl;

    return a + b;
}
int main() {
    int outputVal;
    int k = 2;
    std::vector<promise<int>> p(k);
    vector<future<int>> f(k);

    f[0] = p[0].get_future();
    f[1] = p[1].get_future();

    std::future<int> fu = std::async(std::launch::async,sampleFunc,std::ref(f));

    std::this_thread::sleep_for(chrono::milliseconds(1000));

    p[0].set_value(2);

    std::this_thread::sleep_for(chrono::milliseconds(3000));

    p[1].set_value(4);

    outputVal = fu.get();

    cout << outputVal << endl;
}

延迟可能具有其他含义,例如ab的值可能尚未准备好(可能我们正在等待其他任务在主线程内发生)。

也就是说,如何从子线程向主线程传递部分数据(如上例所示)?可以将这种数据传输模型扩展到其他线程(子线程到另一个子线程)吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用“经典解决方案”在线程shared_ptr之间共享数据。我不认为promisefuture可以(通常)用于传输部分数据:“请注意,std :: promise对象只能使用一次。” (cppreference.com:here)。 我修改了您的代码(有点)以表明我的观点,如果有麻烦,请回来:

#include "bits/stdc++.h"
using namespace std;

//  only a string, but a structure is more general
struct Transfer {
    std::string m_status;

    Transfer() noexcept {};
    Transfer(const std::string& status) : m_status(status)
    {};
};

// std::atomic_shared_ptr is a (new) alternative to this use of std::shared_ptr

//  warning: atomic functions for shared pointers do work on the shared 
//      pointer, not on the contained data 
int sampleFunc(vector<future<int>> &f, std::shared_ptr<Transfer>& status) {

    std::atomic_store(&status, std::make_shared<Transfer>("Waiting for the first result ..."));

    int a = f[0].get();

    std::this_thread::sleep_for(chrono::milliseconds(100)); // to "sync" the output
    cout << "got a from promise 1" << endl;

    std::atomic_store(&status, std::make_shared<Transfer>("Waiting for the second result ..."));

    int b = f[1].get();

    std::this_thread::sleep_for(chrono::milliseconds(100));  //to "sync" the output
    cout << "got b from promise 2" << endl;

    std::atomic_store(&status, std::make_shared<Transfer>("Finishing ..."));

    std::this_thread::sleep_for(chrono::seconds(1));

    return a + b;
}

int main() {
    int outputVal;
    int k = 2;
    std::vector<promise<int>> p(k);
    vector<future<int>> f(k);

    f[0] = p[0].get_future();
    f[1] = p[1].get_future();

    std::shared_ptr<Transfer> status_shared = std::make_shared<Transfer>("Started");
    //  do not forget to use std::ref
    std::future<int> fu = std::async(std::launch::async, sampleFunc, std::ref(f), std::ref(status_shared));

    const auto wait_for_1 = std::async(std::launch::async, [](promise<int>& p) {
        std::this_thread::sleep_for(chrono::milliseconds(1000));
        p.set_value(2);
    }, std::ref(p[0]));

    const auto wait_for_2 = std::async(std::launch::async, [](promise<int>& p) {
        std::this_thread::sleep_for(chrono::milliseconds(3000));
        p.set_value(4);
    }, std::ref(p[1]));

    do {
        const auto status = std::atomic_load(&status_shared);
        cout << status->m_status << '\n';
    } while (future_status::timeout == fu.wait_for(chrono::seconds(1)));

    outputVal = fu.get();

    cout << outputVal << endl;

    return 0;
}