Created
November 23, 2014 03:05
-
-
Save zhaoyk/8442b70b0cafcc6b11f2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| import thread | |
| import time | |
| def real_add(a, b, cb): | |
| def add(): | |
| print("[LOG] count add (%d + %d)...." % (a, b)) | |
| time.sleep(3) | |
| c = a + b | |
| print("[LOG] count add done (%d + %d = %d)." % (a, b, c)) | |
| cb(c) | |
| thread.start_new_thread(add, ()) | |
| def add_task(a, b): | |
| def _add_task(cb): | |
| real_add(a, b, cb) | |
| return _add_task | |
| ############################### | |
| def my_task(): | |
| print("before task") | |
| c = yield add_task(1, 2) | |
| print("middle task c: %d" % c) | |
| d = yield add_task(c, 10) | |
| print("end task %d" % d) | |
| def start_task(gen): | |
| def cb(result): | |
| try: | |
| task = gen.send(result) | |
| except StopIteration: | |
| return | |
| task(cb) | |
| cb(None) | |
| start_task(my_task()) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
从 http://code.activestate.com/recipes/577129-run-asynchronous-tasks-using-coroutines/ 学习来的