繁体   English   中英

C++ 如何使用 std::promise 与可连接线程通信?

[英]C++ How to communicate with a joinable thread using std::promise?

我对如何实现std::promise进行线程间通信感到非常困惑。

这是一个小例子。 当我尝试编译它时,我收到错误“get is not a member of std::promise”。

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

void printer_function(std::promise<int>* the_promise)
{

    // this function should wait for the promise / future ?????

    int the_value = the_promise->get();
    std::cout << the_value << std::endl;

    return; // will be .join()'ed

}

void worker_function()
{

    std::promise<int> the_promise;
    std::future<int> the_future = the_promise.get_future();

    std::thread t(printer_function, &the_promise);

    int the_value = 10;

    // somehow set the value of the promise / future and trigger a notification to printer_function ?
    the_promise.set_value(the_value); // ?????

    t.join(); // join printer_function here

}

int main(int argc, char** argv)
{
    std::thread t(worker_function);

    t.join();

    return 0;
}

您混淆了std::futurestd::promise的角色。

std::future<T>是尚不存在的T结果的占位符。 它生成std::promise<T> object 应将承诺的结果放入其中。

在您的情况下,打印机 function 是结果的接收者 - 使用std::future 工人 function 负责生成结果 - 使用std::promise

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

void printer_function(std::future<int> result)
{
    int the_value = result.get();
    std::cout << the_value << std::endl;

    return; // will be .join()'ed

}

void worker_function()
{

    std::promise<int> the_promise;
    std::future<int> the_future = the_promise.get_future();

    std::thread t(printer_function, std::move(the_future));

    int the_value = 10;

    
    the_promise.set_value(the_value);

    t.join(); // join printer_function here

}

int main(int argc, char** argv)
{
    std::thread t(worker_function);

    t.join();

    return 0;
}

Fixed your example:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM