diff --git a/concurrency/async_fibonacci.py b/concurrency/async_fibonacci.py new file mode 100644 index 0000000..0418b89 --- /dev/null +++ b/concurrency/async_fibonacci.py @@ -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()) diff --git a/concurrency/coroutine_asyncio.py b/concurrency/coroutine_asyncio.py deleted file mode 100644 index ed07b8e..0000000 --- a/concurrency/coroutine_asyncio.py +++ /dev/null @@ -1,24 +0,0 @@ -""" -Example of a coroutine with asyncio -""" - -import asyncio - -@asyncio.coroutine -def factorial(name, number): - f = 1 - for i in range(2, number+1): - print("Task %s: Compute factorial(%s)..." % (name, i)) - yield from asyncio.sleep(1) - f *= i - print("Task %s: factorial(%s) = %s" % (name, number, f)) - - -loop = asyncio.get_event_loop() -tasks = [ - asyncio.ensure_future(factorial("A", 2)), - asyncio.ensure_future(factorial("B", 3)), - asyncio.ensure_future(factorial("C", 4)) - ] -loop.run_until_complete(asyncio.wait(tasks)) -loop.close() \ No newline at end of file diff --git a/concurrency/fibonacci.py b/concurrency/fibonacci.py new file mode 100644 index 0000000..c5b6d9e --- /dev/null +++ b/concurrency/fibonacci.py @@ -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") diff --git a/concurrency/multithreading.py b/concurrency/multithreading.py deleted file mode 100644 index ba6aa1d..0000000 --- a/concurrency/multithreading.py +++ /dev/null @@ -1,24 +0,0 @@ - -# adopted from http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/ - -import threading -import time -import random - - -number = 1 - -class MyThread (threading.Thread): - - def run(self): - global number - print('This is thread ' + str(number) + ' speaking.') - n = number - number += 1 - for i in range(20): - print('Thread', n, 'counts', i) - time.sleep(1 * random.randint(1, 10)) - - -for x in range(10): - MyThread().start() diff --git a/concurrency/subprocess_fibonacci.py b/concurrency/subprocess_fibonacci.py new file mode 100644 index 0000000..ce4e592 --- /dev/null +++ b/concurrency/subprocess_fibonacci.py @@ -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()) diff --git a/concurrency/thread_fibonacci.py b/concurrency/thread_fibonacci.py new file mode 100644 index 0000000..0b040d5 --- /dev/null +++ b/concurrency/thread_fibonacci.py @@ -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()