Skip to content

Commit

Permalink
update concurrency examples
Browse files Browse the repository at this point in the history
  • Loading branch information
Kristian Rother committed Sep 18, 2024
1 parent e95e80b commit 15e7817
Show file tree
Hide file tree
Showing 6 changed files with 106 additions and 48 deletions.
37 changes: 37 additions & 0 deletions concurrency/async_fibonacci.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""
Example of parallel execution with asyncio
see:
https://docs.python.org/3/library/asyncio-task.html
"""
import asyncio
import random
from functools import reduce


def multiply(a, b):
return a * b


async def factorial(number):
"""delayed calculation of fibonacci number"""
result = reduce(multiply, range(1, number + 1), 1)
delay = random.randint(5, 20)
await asyncio.sleep(delay)
print(f"after {delay:2} seconds: {number}! = {result}")


async def main():
# create concurrent tasks
tasks = []
for i in range(10):
tasks.append(asyncio.create_task(factorial(i)))

# wait for tasks to finish
# (all have to be awaited)
for t in tasks:
await t


# run the toplevel async function
asyncio.run(main())
24 changes: 0 additions & 24 deletions concurrency/coroutine_asyncio.py

This file was deleted.

14 changes: 14 additions & 0 deletions concurrency/fibonacci.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import sys
import time
import random

n = int(sys.argv[1])
result = 1

while n > 0:
result *= n
n -= 1

delay = random.randint(5, 15)
time.sleep(delay)
print(f"fibonacci of {sys.argv[1]} = {result} after {delay} sec")
24 changes: 0 additions & 24 deletions concurrency/multithreading.py

This file was deleted.

24 changes: 24 additions & 0 deletions concurrency/subprocess_fibonacci.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""
Launch processes with the subprocess module
https://docs.python.org/3/library/subprocess.html
"""

import subprocess

# launch a single external process
# r = subprocess.run(["python", "fibonacci.py", str(5)])
# try some other command than Python


procs = []
for i in range(10):
cmd = ["python", "fibonacci.py", str(i)]
p = subprocess.Popen(cmd) # , stdout=subprocess.PIPE)
# add stdout argument to see results immediately
procs.append(p)

for p in procs:
p.wait()
# read output from pipe
#print(p.stdout.read().encode())
31 changes: 31 additions & 0 deletions concurrency/thread_fibonacci.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""
Fibonacci with threads
# adopted from
http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/
"""

import threading
import time
import random


class FibonacciThread(threading.Thread):
def __init__(self, number):
super().__init__()
self.number = number

@staticmethod
def fibo(n):
if n == 0:
return 1
else:
return n * FibonacciThread.fibo(n - 1)

def run(self):
result = self.fibo(self.number)
time.sleep(random.randint(5, 20))
print(f"{self.number}! = {result}")


for number in range(10):
FibonacciThread(number).start()

0 comments on commit 15e7817

Please sign in to comment.