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
class Exchanger:
def __init__(self, child=None):
self.child = id(child)
self.to_parent = gevent.queue.Queue()
self.to_child = gevent.queue.Queue()
#односторонняя отправка/получение
def send(self, data):
queue = self._get_queue(queue_for_send=True)
queue.put(data)
def recv(self, wait=False):
queue = self._get_queue()
try:
return queue.get(block=wait)
except Empty, e:
return
#двухсторонний обмен
def get(self, data):
self.send(data)
return self.recv(wait=True)
#
def is_empty(self):
queue = self._get_queue()
return queue.empty()
def clear_all(self):
self._clear(self.to_child)
self._clear(self.to_parent)
#
def _clear(self, queue):
while not queue.empty():
queue.get()
def _is_child(self):
return self.child == self._thread_id()
def _get_queue(self, queue_for_send=False):
if self._is_child() ^ queue_for_send:
return self.to_child
else:
return self.to_parent
def _thread_id(self):
return id(gevent.getcurrent())