Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blocking on many locks/futures/etc. until any is ready

Is it possible to block on a group of locks/futures/any blockable entities, until any one of them is ready? The idea is that we can do:

std::vector<std::future<T>> futures = ...;
auto ready_future = wait_until_an_element_is_ready(futures);
process(ready_future.get());

I remember libraries like libevent, libev, and libuv have this kind of ability for IO tasks. But I don't know if these can be done for locks/futures.

A way I thought of to sort of achieve this is to have the futures call a handler upon completion, but at the same time compare-and-exchange the handler to null so that no other futures can call it. This requires the coordination of the futures, however, so can't be done for locks.

UPDATE: There seems to be a proposal for it for C++2x.

like image 938
Zizheng Tai Avatar asked Jan 15 '17 09:01

Zizheng Tai


1 Answers

If you have boost available, its threading capabilities far exceed the standard library.

This will be the case after c++17, and by the looks of things, even after c++20.

#include <future>
#include <vector>

#define BOOST_THREAD_VERSION 4
#include <boost/thread.hpp>


void wait_for_any(std::vector<boost::future<void>> & v)
{
    boost::wait_for_any(std::begin(v), std::end(v));
}
like image 81
Richard Hodges Avatar answered Nov 03 '22 12:11

Richard Hodges