简体   繁体   中英

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.

Here's a small example. When I try to compile this I get the error "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::future<T> is a placeholder for T result that does not exist yet. It generates std::promise<T> object into which the promised result should be placed.

In your case the printer function is the recipient of the result - use std::future . The worker function is responsible for generating the result - use 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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