summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorVictor Stinner <victor.stinner@gmail.com>2013-12-03 16:37:31 (GMT)
committerVictor Stinner <victor.stinner@gmail.com>2013-12-03 16:37:31 (GMT)
commitc6fba92ebc552da59896a280beb43bfb4f915555 (patch)
tree61f6f15fcfbba0b4c9635bafbaeb20b49b3c5ddd /Doc
parentcc157516a91b49deeed52eb7c98a0959110cb1bf (diff)
downloadcpython-c6fba92ebc552da59896a280beb43bfb4f915555.zip
cpython-c6fba92ebc552da59896a280beb43bfb4f915555.tar.gz
cpython-c6fba92ebc552da59896a280beb43bfb4f915555.tar.bz2
asyncio doc: add one more example of coroutines
Diffstat (limited to 'Doc')
-rw-r--r--Doc/library/asyncio-task.rst66
1 files changed, 65 insertions, 1 deletions
diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst
index e55f962..3c031a0 100644
--- a/Doc/library/asyncio-task.rst
+++ b/Doc/library/asyncio-task.rst
@@ -231,10 +231,14 @@ Task functions
the timeout occurs are returned in the second set.
+Examples
+--------
+
+
.. _asyncio-hello-world-coroutine:
Example: Hello World (coroutine)
---------------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Print ``Hello World`` every two seconds, using a coroutine::
@@ -253,3 +257,63 @@ Print ``Hello World`` every two seconds, using a coroutine::
.. seealso::
:ref:`Hello World example using a callback <asyncio-hello-world-callback>`.
+
+Example: Chains coroutines and parallel execution
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Example chaining coroutines and executing multiple coroutines in parallel::
+
+ import asyncio
+
+ @asyncio.coroutine
+ def compute(x, y):
+ print("Start computing %s + %s" % (x, y))
+ yield from asyncio.sleep(3.0)
+ return x + y
+
+ @asyncio.coroutine
+ def print_sum(x, y):
+ result = yield from compute(x, y)
+ print("%s + %s = %s" % (x, y, result))
+
+ @asyncio.coroutine
+ def wait_task(task):
+ while 1:
+ done, pending = yield from asyncio.wait([task], timeout=1.0)
+ if done:
+ break
+ print("Compute in progress...")
+ asyncio.get_event_loop().stop()
+
+ print("Schedule tasks")
+ task = asyncio.async(print_sum(1, 2))
+ asyncio.async(wait_task(task))
+
+ print("Execute tasks")
+ loop = asyncio.get_event_loop()
+ loop.run_forever()
+ loop.close()
+
+
+
+Output::
+
+ Schedule tasks
+ Execute tasks
+ Start computing 1 + 2
+ Compute in progress...
+ Compute in progress...
+ 1 + 2 = 3
+
+Details:
+
+* ``compute()`` is chained to ``print_sum()``: ``print_sum()`` coroutine waits
+ until ``compute()`` is complete. Coroutines are executed in parallel:
+ ``wait_task()`` is executed while ``compute()`` is blocked in
+ ``asyncio.sleep(3.0)``.
+
+* Coroutines are not executed before the loop is running: ``"Execute tasks"``
+ is written before ``"Start computing 1 + 2"``.
+
+* ``wait_task()`` stops the event loop when ``print_sum()`` is done.
+