Skip to content

Commit

Permalink
Add fibonacci examples that uses futures (#284)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenqie authored Dec 29, 2024
1 parent a9c60f0 commit 5b002c2
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
18 changes: 18 additions & 0 deletions examples/fibonacci/README.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@

**Recursive Parallel Fibonacci**

These examples calculate the Fibonacci number at a given index provided
by the user.

This example is meant to illustrate the use of ``charm.pool`` and nested
parallelism (creating parallel tasks from other parallel tasks).

**Different versions**

There are 3 implementations:

- fib.py (Uses the charm pool to create tasks recursively and assign them to workers)
- fib-numba.py (Uses the Numba JIT compiler for an efficient implementation)
- fibonacci_with_futures.py (Uses Charm4Py futures to store the results of intermediate calculations)

**Usage**

$ python3 -m charmrun.start +p<N> <file_name> <index>

where N is the number of PEs and index is the Fibonacci number you want to calculate. For example, index=6
should return 8.
57 changes: 57 additions & 0 deletions examples/fibonacci/fibonacci_with_futures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from charm4py import charm, Chare, Future, coro
#modeled after the charm with futures example in the charm++ textbook

THRESHOLD = 20

class Fib(Chare):

@coro
def __init__(self, n, future):
if n < THRESHOLD:
res = self.seqFib(n)
future.send(res)
else:
# Create two futures for the recursive calls
f1 = Future()
f2 = Future()

# Create two new chares with parameters n - 1, n - 2, and their corresponding futures
childfib1 = Chare(Fib, args=[n - 1, f1])
childfib2 = Chare(Fib, args=[n - 2, f2])

# Wait for the results
val1 = f1.get()
val2 = f2.get()
res = val1 + val2

# Send result back to the parent chare
future.send(res)

def seqFib(self, n):
if n <= 1:
return n
else:
return self.seqFib(n - 1) + self.seqFib(n - 2)

@coro
def main(args):
if len(args) < 2:
print("Possible Usage: charmrun ++local +p4 fibonacciWithFutures.py 20 <n>")
charm.exit()
n = int(args[1])
if n < 0:
print("n must be a non-negative integer")
charm.exit()

# Create a future
f = Future()

# Create a Fib chare to start the calculations
fibChare = Chare(Fib, args=[n, f])

# Get the value of the future (blocks until received)
res = f.get()
print("The requested Fibonacci number is:", res)
charm.exit()

charm.start(main)

0 comments on commit 5b002c2

Please sign in to comment.