multithreading - Shared future setting different values with get -
i wanted know if shared_futures
. have 2 threads receive reference promise. incase of thread returns output setting value in promise process output , return listening assignment promise remaining thread. can this.
void ta(std::promise<string>& p ) { .... std::string r = "hello thread a"; p.set_value(std::move(r)); } void tb(std::promise<string>& p ) { ... std::string r = "hello thread a"; p.set_value(std::move(r)); } int main() { std::promise<std::string> inputpromise; std::shared_future<std::string> inputfuture(inputpromise.get_future()); //start thread std::thread t(std::bind(&ta,std::ref(inputpromise)); //start thread b std::thread t(std::bind(&ta,std::ref(inputpromise)); std::future<std::string> f(p.get_future()); std::string response = f.get(); ------> unblock when 1 thread sets value promise , can go listening more assignments on promise ? if(response=="b") response = f.get(); -->listen assignment remaining thread }
you cannot call promise::set_value
(or equivalent function set_exception
) more once. promises not intended used in way, shared across threads. have 1 thread owns promise, , 1 or more locations can tell if promise has been satisfied, , if retrieve value.
a promise not right tool doing want. future/promise special case of more general tool: concurrent queue. in true concurrent queue, generating threads push values queue. receiving threads can extract values queue. future/promise single-element queue.
you need general concurrent queue, not single-element queue. unfortunately, standard library doesn't have one.
Comments
Post a Comment