The following code demonstrates the using of python 3.5 coroutines in order to implement async IO
import asynciofrom threading import Thread, current_threadimport datetimeprint (current_thread())async def compute(x, y):print("Compute %s + %s ... Current thread:%s" % (x, y , current_thread() ))await asyncio.sleep(1.0)return x + yasync def print_sum(x, y):print (current_thread())result = await compute(x, y)print("%s + %s = %s" % (x, y, result))loop = asyncio.get_event_loop()theTask1 = loop.create_task(print_sum(1, 2))theTask2 = loop.create_task(print_sum(4, 2))theTask3 = loop.create_task(print_sum(14, 2))tasks = [theTask1,theTask2,theTask3]loop.run_until_complete(asyncio.wait(tasks))loop.close()
And the result:
<_MainThread(MainThread, started 1696)>
<_MainThread(MainThread, started 1696)>
Compute 1 + 2 ... Current thread:<_MainThread(MainThread, started 1696)>
<_MainThread(MainThread, started 1696)>
Compute 4 + 2 ... Current thread:<_MainThread(MainThread, started 1696)>
<_MainThread(MainThread, started 1696)>
Compute 14 + 2 ... Current thread:<_MainThread(MainThread, started 1696)>
1 + 2 = 3
4 + 2 = 6
14 + 2 = 16
References
https://docs.python.org/3/library/asyncio-task.html
http://wla.berkeley.edu/~cs61a/fa11/lectures/streams.html#coroutines
אין תגובות:
הוסף רשומת תגובה