Last active
December 21, 2015 22:29
-
-
Save xjdrew/6376044 to your computer and use it in GitHub Desktop.
用gevent变异步调用为同步
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
import gevent | |
from gevent.queue import Queue | |
q = Queue() | |
session = {} | |
def producer(): | |
i = 1 | |
while True: | |
q.put(i) | |
i = i + 1 | |
gevent.sleep(1) | |
def dispatch(): | |
while True: | |
i = q.get() | |
try: | |
g1 = session[i] | |
except: | |
print("in dispatch:", i) | |
continue | |
gevent.spawn(g1.switch, i) | |
def wait(i): | |
gl = gevent.getcurrent() | |
session[i] = gl | |
return gevent.get_hub().switch() | |
def logic(): | |
v = wait(5) | |
print("in logic:", v) | |
v = wait(8) | |
print("in logic:", v) | |
return 5 | |
gevent.spawn(producer) | |
gevent.spawn(dispatch) | |
gevent.spawn(logic) | |
gevent.sleep(20) |
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
import gevent | |
from gevent.queue import Queue | |
from gevent.event import AsyncResult | |
q = Queue() | |
session = {} | |
def producer(): | |
i = 1 | |
while True: | |
q.put(i) | |
i = i + 1 | |
gevent.sleep(1) | |
def dispatch(): | |
while True: | |
i = q.get() | |
try: | |
a = session[i] | |
except: | |
print("in dispatch:", i) | |
continue | |
a.set(i) | |
def wait(i): | |
a = AsyncResult() | |
session[i] = a | |
return a.get() | |
def logic(): | |
v = wait(5) | |
print("in logic:", v) | |
v = wait(8) | |
print("in logic:", v) | |
return 5 | |
gevent.spawn(producer) | |
gevent.spawn(dispatch) | |
gevent.spawn(logic) | |
gevent.sleep(20) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment