Python Desktop Server Weblog 27.12.2004

a picture of myself

Münsterland.org

2004-12-27

Futures as a different kind of Promise

Futures are just Promises - I was reminded of this fact by the Alice Tour. So I just added futures to my lazy evaluation module. Futures are just promises that are not calculated when the result is needed, but that start calculating the value right along - in parallel to your main thread. So every future represents a thread that calculates some result. When you force the result of a future that isn't already done, your main thread will block until the future is done and then continue with either the value or the exception of the calculated future. It's a nice and clean way to do multithreading in a small scale:

from LazyEvaluation import *

# define the fibonacci function
def fib(n):
    
if n in (0,1): return 1
    
else: return fib(n-1) + fib(n-2)

# make fib a future generating function
ffib = future(fib)

# create some future promises
fib5 = ffib(5)
fib10 = ffib(10)
fib20 = ffib(20)
fib30 = ffib(30) # that one takes quite long

# calculate some fibonacci number in the foreground while
# other calculations proceed in the background
# (due to the GIL in Python this won't make use of multiple
# processors and so can be seen as a purely academic
# exercise!)
fib15 = fib(15)

# now print the values - this will force the values
# and will block until the value is available
print fib5
print fib10
print fib15
print fib20
print fib30
This post references topics: python
posted at 21:26:40    #
December 2004
MoTuWeThFrSaSu
   1 2 3 4 5
6 7 8 9101112
13141516171819
20212223242526
2728293031  
Nov
2004
 Jan
2005

This is the Python Desktop Server weblog.


(Donations will be used by the author to buy stuff, fullfill selfish wishes or do other silly recreational things. You have been warned.).
The PyDS is
OSI Certified Open Source Software

Python Powered

XML-Image

© 2004-2007, Georg Bauer