0

I want to use futures in a multithreaded C++ application. The value associated to a certain promise should be read by more than one thread. I though boost::shared_future is meant to be used for that, but unfortunately I can read the value only once.

How can I read the value multiple times?

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: "

(To support older compilers (MSVC...) I want to use Boost instead of the new C++11 stuff.)

Thanks in advance!

arngineer
  • 105
  • 1
  • 1
  • 8
  • Specify your compiler and boost version, please. With g++ 4.8.0 and boost 1.51 I got three lines with "Hello world" in each. – awesoon Sep 20 '12 at 09:06
  • 1
    Don't know about Boost, but the behavior you're expecting is exactly what's specified for `std::shared_future::get()`. – Pete Becker Sep 20 '12 at 12:18
  • Ok, I just updated to Boost v1.51.0, and now it works as expected, so I guess this is a Boost bug. Sorry for the inconvenience. – arngineer Sep 20 '12 at 13:16

0 Answers0