-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgevent_channels.py
57 lines (42 loc) · 1.33 KB
/
gevent_channels.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, division
from gevent import wait
from gevent.event import Event
from gevent.queue import Queue
class Channel:
def __init__(self):
self.event = Event()
self.event.channel = self
self.queue = Queue(maxsize=1)
def put(self, e):
self.queue.put(e)
self.event.set()
def channel_wait(channels, timeout=None):
assert all(isinstance(channel, Channel) for channel in channels), "Can only wait on channels"
event = wait([channel.event for channel in channels], timeout, 1)
if event:
val = event[0].channel.queue.get_nowait()
event[0].clear()
return val, event[0].channel
if __name__ == "__main__":
from gevent import sleep, spawn, joinall
hey, hola = Channel(), Channel()
def g():
for i in range(100):
msg, channel = channel_wait([hey, hola])
if channel == hey:
print 'hey %s' % msg
else:
print 'hola %s' % msg
sleep(5)
def f():
for i in range(100):
if i % 3 == 1:
hey.put(i)
print 'put %s in hey' % i
else:
hola.put(i)
print 'put %s in hola' % i
g_f = spawn(f)
g_g = spawn(g)
joinall([g_f, g_g])