1 | n/a | # |
---|
2 | n/a | # Analogue of `multiprocessing.connection` which uses queues instead of sockets |
---|
3 | n/a | # |
---|
4 | n/a | # multiprocessing/dummy/connection.py |
---|
5 | n/a | # |
---|
6 | n/a | # Copyright (c) 2006-2008, R Oudkerk |
---|
7 | n/a | # Licensed to PSF under a Contributor Agreement. |
---|
8 | n/a | # |
---|
9 | n/a | |
---|
10 | n/a | __all__ = [ 'Client', 'Listener', 'Pipe' ] |
---|
11 | n/a | |
---|
12 | n/a | from queue import Queue |
---|
13 | n/a | |
---|
14 | n/a | |
---|
15 | n/a | families = [None] |
---|
16 | n/a | |
---|
17 | n/a | |
---|
18 | n/a | class Listener(object): |
---|
19 | n/a | |
---|
20 | n/a | def __init__(self, address=None, family=None, backlog=1): |
---|
21 | n/a | self._backlog_queue = Queue(backlog) |
---|
22 | n/a | |
---|
23 | n/a | def accept(self): |
---|
24 | n/a | return Connection(*self._backlog_queue.get()) |
---|
25 | n/a | |
---|
26 | n/a | def close(self): |
---|
27 | n/a | self._backlog_queue = None |
---|
28 | n/a | |
---|
29 | n/a | address = property(lambda self: self._backlog_queue) |
---|
30 | n/a | |
---|
31 | n/a | def __enter__(self): |
---|
32 | n/a | return self |
---|
33 | n/a | |
---|
34 | n/a | def __exit__(self, exc_type, exc_value, exc_tb): |
---|
35 | n/a | self.close() |
---|
36 | n/a | |
---|
37 | n/a | |
---|
38 | n/a | def Client(address): |
---|
39 | n/a | _in, _out = Queue(), Queue() |
---|
40 | n/a | address.put((_out, _in)) |
---|
41 | n/a | return Connection(_in, _out) |
---|
42 | n/a | |
---|
43 | n/a | |
---|
44 | n/a | def Pipe(duplex=True): |
---|
45 | n/a | a, b = Queue(), Queue() |
---|
46 | n/a | return Connection(a, b), Connection(b, a) |
---|
47 | n/a | |
---|
48 | n/a | |
---|
49 | n/a | class Connection(object): |
---|
50 | n/a | |
---|
51 | n/a | def __init__(self, _in, _out): |
---|
52 | n/a | self._out = _out |
---|
53 | n/a | self._in = _in |
---|
54 | n/a | self.send = self.send_bytes = _out.put |
---|
55 | n/a | self.recv = self.recv_bytes = _in.get |
---|
56 | n/a | |
---|
57 | n/a | def poll(self, timeout=0.0): |
---|
58 | n/a | if self._in.qsize() > 0: |
---|
59 | n/a | return True |
---|
60 | n/a | if timeout <= 0.0: |
---|
61 | n/a | return False |
---|
62 | n/a | with self._in.not_empty: |
---|
63 | n/a | self._in.not_empty.wait(timeout) |
---|
64 | n/a | return self._in.qsize() > 0 |
---|
65 | n/a | |
---|
66 | n/a | def close(self): |
---|
67 | n/a | pass |
---|
68 | n/a | |
---|
69 | n/a | def __enter__(self): |
---|
70 | n/a | return self |
---|
71 | n/a | |
---|
72 | n/a | def __exit__(self, exc_type, exc_value, exc_tb): |
---|
73 | n/a | self.close() |
---|