简体   繁体   English

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

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

I'm very confused as to how to implement std::promise for inter-thread communication.我对如何实现std::promise进行线程间通信感到非常困惑。

Here's a small example.这是一个小例子。 When I try to compile this I get the error "get is not a member of 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;
}

You have mixed up the roles of std::future and std::promise .您混淆了std::futurestd::promise的角色。

std::future<T> is a placeholder for T result that does not exist yet. std::future<T>是尚不存在的T结果的占位符。 It generates std::promise<T> object into which the promised result should be placed.它生成std::promise<T> object 应将承诺的结果放入其中。

In your case the printer function is the recipient of the result - use std::future .在您的情况下,打印机 function 是结果的接收者 - 使用std::future The worker function is responsible for generating the result - use std::promise .工人 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