C++ C++;如何使用std::promise与可连接线程通信?
对于如何为线程间通信实现C++ C++;如何使用std::promise与可连接线程通信?,c++,multithreading,promise,future,C++,Multithreading,Promise,Future,对于如何为线程间通信实现std::promise,我感到非常困惑 这里有一个小例子。当我试图编译它时,我得到一个错误“get不是std::promise的成员” #包括 #包括 #包括 无效打印机_函数(std::promise*the_promise) { //此功能应等待承诺/未来????? int the_value=the_promise->get(); std::cout您混淆了std::future和std::promise的角色 #include <iostream>
std::promise
,我感到非常困惑
这里有一个小例子。当我试图编译它时,我得到一个错误“get不是std::promise的成员”
#包括
#包括
#包括
无效打印机_函数(std::promise*the_promise)
{
//此功能应等待承诺/未来?????
int the_value=the_promise->get();
std::cout您混淆了std::future
和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:
std::future
是尚未存在的T
结果的占位符。它生成std::promise
对象,承诺的结果应放在该对象中
在您的情况下,打印机函数是结果的接收者-使用std::future
。
worker函数负责生成结果-usestd::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:
#包括
#包括
#包括
无效打印机功能(标准::未来结果)
{
int_值=result.get();
std::cout我从来没有见过用于线程通信的承诺。通常,这是通过原子变量或条件变量实现的。之所以会出现错误,正是因为std::promise
s没有get
memebr函数。此外,将原始指针的问题添加到多线程的问题上肯定没有帮助。啊!Simp错误。我今天有太多事情要做,我显然没有思考straight@FreelanceConsultant发生在我们当中最好的人身上:)