簡體   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