使用 get 共享未来设置不同的值

Shared future setting different values with get

我想知道我是否可以用 shared_futures 做这样的事情。 本质上,我有两个线程接收对承诺的引用。 如果任何线程 return 通过在 promise 中设置一个值来输出,我想处理该输出,然后 return 返回侦听来自剩余线程的对 promise 的另一个分配。我可以做这样的事情吗?

void tA(std::promise<string>& p )
{
  ....
  std::string r = "Hello from thread A";
  p.set_value(std::move(r));
}

void tB(std::promise<string>& p )
{
  ...
  std::string r = "Hello from 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 the thread A
std::thread t(std::bind(&tA,std::ref(inputpromise));

//start the thread B
std::thread t(std::bind(&tA,std::ref(inputpromise));

std::future<std::string> f(p.get_future());

std::string response = f.get(); ------> Will this unblock when one thread sets a value to the promise and can i go back listening for more assignments on the promise ?

if(response=="b")

response = f.get(); -->listen for the assignment from the remaining thread
}

您不能多次调用 promise::set_value(或任何等效函数,如 set_exception)。 Promises 不打算以这种方式使用,跨线程共享。您有一个拥有承诺的线程,以及一个或多个位置,可以判断承诺是否已得到满足,如果满足则检索值。

承诺不是做你想做的事情的正确工具。 future/promise 实际上是更通用工具的特例:并发队列。在真正的并发队列中,生成线程将值推入队列。接收线程可以从队列中提取值。 future/promise 本质上是一个单元素队列。

你需要一个通用的并发队列,而不是单元素队列。不幸的是,标准库没有。