Boost logo

Boost Users :

Subject: Re: [Boost-users] [boost::thread] using futures
From: Anthony Williams (anthony.ajw_at_[hidden])
Date: 2011-05-09 16:26:39


Kazz <sfx810_at_[hidden]> writes:

> Hi All. I am trying to use Futures, but not getting the expected result. The
> code below works some times, and other times it throws exception
>
> "terminate called after throwing an instance of
> 'boost::exception_detail::clone_impl
> <boost::exception_detail::error_info_injector<boost::promise_already_satisfied>
>>'
>   what():  Promise already satisfied"

That exception is thrown if you call set_value a second time on the same
promise.

> boost::promise<int> pt;    // holds final calculated result
>
> void worker1()
> {
>     pt.set_value(1);
> }
>
> void worker2()
> {
>     pt.set_value(2);
> }

Both workers set the same promise. One of them will therefore throw, if
they both get to the set_value. An uncaught exception in a thread will
terminate the application.

> int main() {
>     boost::shared_future<int> ans(pt.get_future());
>
>     boost::thread th1(worker1);
>     boost::thread th2(worker2);
>
>     ans.wait();
>
>     std::cout<<ans.get()<<std::endl;
>
>     std::cout<<"exiting"<<std::endl;
>
>     return 0;
> }

Both threads are detached here, and then the process exits. If
the second thread to call set_value is still sleeping, so hasn't yet got
to the set_value call, it will be terminated normally as part of process
exit. If the second thread gets to the set_value call before the process
exits it will abort the process due to the unhandled exception.

Anthony

-- 
Author of C++ Concurrency in Action     http://www.stdthread.co.uk/book/
just::thread C++0x thread library             http://www.stdthread.co.uk
Just Software Solutions Ltd       http://www.justsoftwaresolutions.co.uk
15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net