@andymitchhank/wielding-threaded-async-magic
Python

Based on the article @ https://tryexceptpass.org/article/threaded-asynchronous-magic-and-how-to-wield-it/

fork
loading
Files
  • main.py
  • decorators.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import asyncio
import signal
from threading import Thread
import time

from decorators import logger


@logger
async def do_some_work(x):
	await asyncio.sleep(x)


@logger
def more_work(x):
	time.sleep(x)


@logger
def block_the_main_thread():
	loop = asyncio.get_event_loop()
	loop.run_until_complete(do_some_work(5))

	tasks = [
	    asyncio.ensure_future(do_some_work(2)),
	    asyncio.ensure_future(do_some_work(5))
	]

	loop.run_until_complete(asyncio.gather(*tasks))


def start_loop(loop):
	asyncio.set_event_loop(loop)
	loop.run_forever()


@logger
def on_a_new_thread():
	new_loop = asyncio.new_event_loop()
	t = Thread(target=start_loop, args=(new_loop, ))
	t.start()

	new_loop.call_soon_threadsafe(more_work, 20)
	asyncio.run_coroutine_threadsafe(do_some_work(5), new_loop)
	last_future = asyncio.run_coroutine_threadsafe(do_some_work(10), new_loop)

	# Since we know which coroutine will finish last,
	# we can stop the loop when it's done
	last_future.add_done_callback(lambda f: new_loop.stop())


if __name__ == '__main__':
	block_the_main_thread()
	on_a_new_thread()
Python 3.6.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux