Skip to content

Instantly share code, notes, and snippets.

@danielhfrank
Created December 1, 2020 20:53
Show Gist options
  • Save danielhfrank/73555fe9fa68f887dbfc57a811a08928 to your computer and use it in GitHub Desktop.
Save danielhfrank/73555fe9fa68f887dbfc57a811a08928 to your computer and use it in GitHub Desktop.
Implementations of concurrent fibonacci numbers in vanilla asyncio and trio
import asyncio
import trio
import sys
async def fib(n: int) -> int:
if n < 0:
raise ValueError('boom')
elif n in {0, 1}:
return 1
else:
results = await asyncio.gather(fib(n-1), fib(n-2))
return sum(results)
async def trio_fib(n: int) -> int:
async with trio.open_nursery() as nursery:
send_chan, recv_chan = trio.open_memory_channel(0)
nursery.start_soon(fib_producer, n, send_chan)
async with recv_chan:
async for val in recv_chan:
return val
async def fib_producer(n: int, out_chan):
if n < 0:
raise ValueError('boom')
elif n in {0, 1}:
async with out_chan:
await out_chan.send(1)
else:
async with trio.open_nursery() as nursery:
send_chan, recv_chan = trio.open_memory_channel(0)
async with send_chan:
nursery.start_soon(fib_producer, n-1, send_chan.clone())
nursery.start_soon(fib_producer, n-2, send_chan.clone())
nursery.start_soon(fib_receiver, recv_chan, out_chan)
async def fib_receiver(in_chan, out_chan):
result = 0
async with in_chan:
async for value in in_chan:
result += value
async with out_chan:
await out_chan.send(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment