Into the Future!

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.

But given that futures are conceptually like a mixture of read-only properties mixed with a subset of the tasklet-functionality, it was just a no-brainer to write them.

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

Comments are closed.


Copyright © 2007 - 2017 by the respective authors.
Permission to use the image of Great Cthulhu has kindly been granted by F. Launet/Goomi Studio.
Other content on this website is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.0 Germany License.
Creative Commons License


Blog directory