Last active
February 8, 2017 05:49
-
-
Save OniOni/61b147351803cd8f99e4f6123b5a75ef to your computer and use it in GitHub Desktop.
This file contains 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 | |
class Pool(object): | |
def __init__(self): | |
self.tasks = [] | |
self._greenlets = [] | |
def apply_async(self, func, *a, **k, callback=None): | |
greenlet = gevent.spawn(func, *a, **k) | |
self._greenlets.append(greenlet) | |
if callback: | |
greenlet.link(callback) | |
return greenlet | |
def apply_all_async(self, triplets): | |
return [ | |
self.apply_async(*t) | |
for t in triplets | |
] | |
def join(self, timeout=None): | |
return [g.get() for g in gevent.wait(self._greenlets, timeout=timeout)] | |
def ijoin(self, timeout=None): | |
return (g.get() for g in gevent.iwait(self._greenlets, timeout=timeout)) | |
def fake(msg, delay): | |
gevent.sleep(delay) | |
print("Slept {} seconds, {}".format(delay, msg)) | |
return delay | |
if __name__ == "__main__": | |
p = Pool() | |
#for i in range(10): | |
# p.apply_async(fake, str(i), 10 - i) | |
p.apply_all_async([(fake, str(i), i) for i in range(10)]) | |
#l = p.join() | |
#print(l) | |
for r in p.ijoin(): | |
print(r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment