Skip to content

Instantly share code, notes, and snippets.

@jordic
Created April 26, 2019 04:47
Show Gist options
  • Save jordic/ab0fc40fc21797b1be113730175e363c to your computer and use it in GitHub Desktop.
Save jordic/ab0fc40fc21797b1be113730175e363c to your computer and use it in GitHub Desktop.
asyncio
import asyncio
async def fibonacci(n: int, c: asyncio.Queue):
i, x, y = 0, 0, 1
while(i < n):
print(f"produccing {i}")
await c.put(x)
x, y = y, x + y
i += 1
async def main():
ch = asyncio.Queue(10)
await fibonacci(10, ch)
while not ch.empty():
val = await ch.get()
print(f'result: {val}')
if __name__ == "__main__":
asyncio.run(main())
import asyncio
async def sum(a: [int], ch: asyncio.Queue) -> None:
res = 0
for k in a:
res += k
ch.put_nowait(res)
async def main():
nums = [1, 1, 1, 1, 1, 1, 1, 1]
result = asyncio.Queue()
t1 = sum(nums[:4], result)
t2 = sum(nums[4:], result)
asyncio.gather(t1, t2)
a = await result.get()
b = await result.get()
print('Result', a, b, a + b)
async def main2():
ch = asyncio.Queue(2)
ch.put_nowait(1)
ch.put_nowait(2)
print(await ch.get())
print(await ch.get())
def run(example, func):
print(f'Runnint {example}')
asyncio.run(func)
if __name__ == "__main__":
run("ex1", main())
run("ex2", main2())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment