我想在多线程 C++ 应用程序中使用期货。与某个 Promise 关联的值应该由多个线程读取。我虽然 boost::shared_future 旨在用于此,但不幸的是我只能读取一次该值。
如何多次读取该值?
boost::promise<std::string> dataProm;
boost::shared_future<std::string> sharedFut1( boost::move(dataProm.get_future()) );
boost::shared_future<std::string> sharedFut2( sharedFut1 );
dataProm.set_value( std::string("Hello World") ); // (in the producer thread)
std::cout << "Test1: " << sharedFut1.get() << std::endl; // (in consumer thread 1), result: "Test1: Hello World"
std::cout << "Test2: " << sharedFut2.get() << std::endl; // (in consumer thread 2), result: "Test2: "
std::cout << "Test3: " << sharedFut1.get() << std::endl; // (in consumer thread 1, again), result: "Test3: "
(为了支持较旧的编译器(MSVC ...),我想使用 Boost 而不是新的 C++11 东西。)
提前致谢!