Triggered by the announcement that boost will soon include futures, I sat down to write a quick implementation myself. Yes, I know, it’s kind of stupid to do something that boost/c++0x will include very soon anyway.
So there you are.
Follow the jump for a quick example on how to use them.
It really couldn’t be simpler: a future is essentially a read-only object of a value type of your choosing, the value of which is calculated in a background thread. When trying to read the value, the code blocks until the background thread has finished:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
using namespace fhtagn::threads; // You need some function to calculate the value with. // You might want to look into boost::lambda if you want // to define it inline. int my_calculating_function(); // A future representing an integer type is instanciated // with the function that calculates is value. This spawns // the background thread immediately. future<int> x(&my_calculating_function); // When reading the value (i.e. using the future in an // expression), the code blocks until the background // thread is finished. int y = 3.1415 * x; // However, once it's calculated, there's no need to run // the thread again, and things are much quicker. int z = x;
Simple, isn’t it? There’s more to it, but not a lot…
Pages: 1 2