| 1 |
"""Cross-interpreter Queues High Level Module.""" |
| 2 |
|
| 3 |
import pickle |
| 4 |
import queue |
| 5 |
import time |
| 6 |
import weakref |
| 7 |
import _interpqueues as _queues |
| 8 |
from . import _crossinterp |
| 9 |
|
| 10 |
# aliases: |
| 11 |
from _interpqueues import ( |
| 12 |
QueueError, QueueNotFoundError, |
| 13 |
) |
| 14 |
from ._crossinterp import ( |
| 15 |
UNBOUND_ERROR, UNBOUND_REMOVE, |
| 16 |
) |
| 17 |
|
| 18 |
__all__ = [ |
| 19 |
'UNBOUND', 'UNBOUND_ERROR', 'UNBOUND_REMOVE', |
| 20 |
'create', 'list_all', |
| 21 |
'Queue', |
| 22 |
'QueueError', 'QueueNotFoundError', 'QueueEmpty', 'QueueFull', |
| 23 |
'ItemInterpreterDestroyed', |
| 24 |
] |
| 25 |
|
| 26 |
|
| 27 |
class QueueEmpty(QueueError, queue.Empty): |
| 28 |
"""Raised from get_nowait() when the queue is empty. |
| 29 |
|
| 30 |
It is also raised from get() if it times out. |
| 31 |
""" |
| 32 |
|
| 33 |
|
| 34 |
class QueueFull(QueueError, queue.Full): |
| 35 |
"""Raised from put_nowait() when the queue is full. |
| 36 |
|
| 37 |
It is also raised from put() if it times out. |
| 38 |
""" |
| 39 |
|
| 40 |
|
| 41 |
class ItemInterpreterDestroyed(QueueError, |
| 42 |
_crossinterp.ItemInterpreterDestroyed): |
| 43 |
"""Raised from get() and get_nowait().""" |
| 44 |
|
| 45 |
|
| 46 |
_SHARED_ONLY = 0 |
| 47 |
_PICKLED = 1 |
| 48 |
|
| 49 |
|
| 50 |
UNBOUND = _crossinterp.UnboundItem.singleton('queue', __name__) |
| 51 |
|
| 52 |
|
| 53 |
def _serialize_unbound(unbound): |
| 54 |
if unbound is UNBOUND: |
| 55 |
unbound = _crossinterp.UNBOUND |
| 56 |
return _crossinterp.serialize_unbound(unbound) |
| 57 |
|
| 58 |
|
| 59 |
def _resolve_unbound(flag): |
| 60 |
resolved = _crossinterp.resolve_unbound(flag, ItemInterpreterDestroyed) |
| 61 |
if resolved is _crossinterp.UNBOUND: |
| 62 |
resolved = UNBOUND |
| 63 |
return resolved |
| 64 |
|
| 65 |
|
| 66 |
def create(maxsize=0, *, syncobj=False, unbounditems=UNBOUND): |
| 67 |
"""Return a new cross-interpreter queue. |
| 68 |
|
| 69 |
The queue may be used to pass data safely between interpreters. |
| 70 |
|
| 71 |
"syncobj" sets the default for Queue.put() |
| 72 |
and Queue.put_nowait(). |
| 73 |
|
| 74 |
"unbounditems" likewise sets the default. See Queue.put() for |
| 75 |
supported values. The default value is UNBOUND, which replaces |
| 76 |
the unbound item. |
| 77 |
""" |
| 78 |
fmt = _SHARED_ONLY if syncobj else _PICKLED |
| 79 |
unbound = _serialize_unbound(unbounditems) |
| 80 |
unboundop, = unbound |
| 81 |
qid = _queues.create(maxsize, fmt, unboundop) |
| 82 |
return Queue(qid, _fmt=fmt, _unbound=unbound) |
| 83 |
|
| 84 |
|
| 85 |
def list_all(): |
| 86 |
"""Return a list of all open queues.""" |
| 87 |
return [Queue(qid, _fmt=fmt, _unbound=(unboundop,)) |
| 88 |
for qid, fmt, unboundop in _queues.list_all()] |
| 89 |
|
| 90 |
|
| 91 |
_known_queues = weakref.WeakValueDictionary() |
| 92 |
|
| 93 |
class Queue: |
| 94 |
"""A cross-interpreter queue.""" |
| 95 |
|
| 96 |
def __new__(cls, id, /, *, _fmt=None, _unbound=None): |
| 97 |
# There is only one instance for any given ID. |
| 98 |
if isinstance(id, int): |
| 99 |
id = int(id) |
| 100 |
else: |
| 101 |
raise TypeError(f'id must be an int, got {id!r}') |
| 102 |
if _fmt is None: |
| 103 |
if _unbound is None: |
| 104 |
_fmt, op = _queues.get_queue_defaults(id) |
| 105 |
_unbound = (op,) |
| 106 |
else: |
| 107 |
_fmt, _ = _queues.get_queue_defaults(id) |
| 108 |
elif _unbound is None: |
| 109 |
_, op = _queues.get_queue_defaults(id) |
| 110 |
_unbound = (op,) |
| 111 |
try: |
| 112 |
self = _known_queues[id] |
| 113 |
except KeyError: |
| 114 |
self = super().__new__(cls) |
| 115 |
self._id = id |
| 116 |
self._fmt = _fmt |
| 117 |
self._unbound = _unbound |
| 118 |
_known_queues[id] = self |
| 119 |
_queues.bind(id) |
| 120 |
return self |
| 121 |
|
| 122 |
def __del__(self): |
| 123 |
try: |
| 124 |
_queues.release(self._id) |
| 125 |
except QueueNotFoundError: |
| 126 |
pass |
| 127 |
try: |
| 128 |
del _known_queues[self._id] |
| 129 |
except KeyError: |
| 130 |
pass |
| 131 |
|
| 132 |
def __repr__(self): |
| 133 |
return f'{type(self).__name__}({self.id})' |
| 134 |
|
| 135 |
def __hash__(self): |
| 136 |
return hash(self._id) |
| 137 |
|
| 138 |
# for pickling: |
| 139 |
def __getnewargs__(self): |
| 140 |
return (self._id,) |
| 141 |
|
| 142 |
# for pickling: |
| 143 |
def __getstate__(self): |
| 144 |
return None |
| 145 |
|
| 146 |
@property |
| 147 |
def id(self): |
| 148 |
return self._id |
| 149 |
|
| 150 |
@property |
| 151 |
def maxsize(self): |
| 152 |
try: |
| 153 |
return self._maxsize |
| 154 |
except AttributeError: |
| 155 |
self._maxsize = _queues.get_maxsize(self._id) |
| 156 |
return self._maxsize |
| 157 |
|
| 158 |
def empty(self): |
| 159 |
return self.qsize() == 0 |
| 160 |
|
| 161 |
def full(self): |
| 162 |
return _queues.is_full(self._id) |
| 163 |
|
| 164 |
def qsize(self): |
| 165 |
return _queues.get_count(self._id) |
| 166 |
|
| 167 |
def put(self, obj, timeout=None, *, |
| 168 |
syncobj=None, |
| 169 |
unbound=None, |
| 170 |
_delay=10 / 1000, # 10 milliseconds |
| 171 |
): |
| 172 |
"""Add the object to the queue. |
| 173 |
|
| 174 |
This blocks while the queue is full. |
| 175 |
|
| 176 |
If "syncobj" is None (the default) then it uses the |
| 177 |
queue's default, set with create_queue(). |
| 178 |
|
| 179 |
If "syncobj" is false then all objects are supported, |
| 180 |
at the expense of worse performance. |
| 181 |
|
| 182 |
If "syncobj" is true then the object must be "shareable". |
| 183 |
Examples of "shareable" objects include the builtin singletons, |
| 184 |
str, and memoryview. One benefit is that such objects are |
| 185 |
passed through the queue efficiently. |
| 186 |
|
| 187 |
The key difference, though, is conceptual: the corresponding |
| 188 |
object returned from Queue.get() will be strictly equivalent |
| 189 |
to the given obj. In other words, the two objects will be |
| 190 |
effectively indistinguishable from each other, even if the |
| 191 |
object is mutable. The received object may actually be the |
| 192 |
same object, or a copy (immutable values only), or a proxy. |
| 193 |
Regardless, the received object should be treated as though |
| 194 |
the original has been shared directly, whether or not it |
| 195 |
actually is. That's a slightly different and stronger promise |
| 196 |
than just (initial) equality, which is all "syncobj=False" |
| 197 |
can promise. |
| 198 |
|
| 199 |
"unbound" controls the behavior of Queue.get() for the given |
| 200 |
object if the current interpreter (calling put()) is later |
| 201 |
destroyed. |
| 202 |
|
| 203 |
If "unbound" is None (the default) then it uses the |
| 204 |
queue's default, set with create_queue(), |
| 205 |
which is usually UNBOUND. |
| 206 |
|
| 207 |
If "unbound" is UNBOUND_ERROR then get() will raise an |
| 208 |
ItemInterpreterDestroyed exception if the original interpreter |
| 209 |
has been destroyed. This does not otherwise affect the queue; |
| 210 |
the next call to put() will work like normal, returning the next |
| 211 |
item in the queue. |
| 212 |
|
| 213 |
If "unbound" is UNBOUND_REMOVE then the item will be removed |
| 214 |
from the queue as soon as the original interpreter is destroyed. |
| 215 |
Be aware that this will introduce an imbalance between put() |
| 216 |
and get() calls. |
| 217 |
|
| 218 |
If "unbound" is UNBOUND then it is returned by get() in place |
| 219 |
of the unbound item. |
| 220 |
""" |
| 221 |
if syncobj is None: |
| 222 |
fmt = self._fmt |
| 223 |
else: |
| 224 |
fmt = _SHARED_ONLY if syncobj else _PICKLED |
| 225 |
if unbound is None: |
| 226 |
unboundop, = self._unbound |
| 227 |
else: |
| 228 |
unboundop, = _serialize_unbound(unbound) |
| 229 |
if timeout is not None: |
| 230 |
timeout = int(timeout) |
| 231 |
if timeout < 0: |
| 232 |
raise ValueError(f'timeout value must be non-negative') |
| 233 |
end = time.time() + timeout |
| 234 |
if fmt is _PICKLED: |
| 235 |
obj = pickle.dumps(obj) |
| 236 |
while True: |
| 237 |
try: |
| 238 |
_queues.put(self._id, obj, fmt, unboundop) |
| 239 |
except QueueFull as exc: |
| 240 |
if timeout is not None and time.time() >= end: |
| 241 |
raise # re-raise |
| 242 |
time.sleep(_delay) |
| 243 |
else: |
| 244 |
break |
| 245 |
|
| 246 |
def put_nowait(self, obj, *, syncobj=None, unbound=None): |
| 247 |
if syncobj is None: |
| 248 |
fmt = self._fmt |
| 249 |
else: |
| 250 |
fmt = _SHARED_ONLY if syncobj else _PICKLED |
| 251 |
if unbound is None: |
| 252 |
unboundop, = self._unbound |
| 253 |
else: |
| 254 |
unboundop, = _serialize_unbound(unbound) |
| 255 |
if fmt is _PICKLED: |
| 256 |
obj = pickle.dumps(obj) |
| 257 |
_queues.put(self._id, obj, fmt, unboundop) |
| 258 |
|
| 259 |
def get(self, timeout=None, *, |
| 260 |
_delay=10 / 1000, # 10 milliseconds |
| 261 |
): |
| 262 |
"""Return the next object from the queue. |
| 263 |
|
| 264 |
This blocks while the queue is empty. |
| 265 |
|
| 266 |
If the next item's original interpreter has been destroyed |
| 267 |
then the "next object" is determined by the value of the |
| 268 |
"unbound" argument to put(). |
| 269 |
""" |
| 270 |
if timeout is not None: |
| 271 |
timeout = int(timeout) |
| 272 |
if timeout < 0: |
| 273 |
raise ValueError(f'timeout value must be non-negative') |
| 274 |
end = time.time() + timeout |
| 275 |
while True: |
| 276 |
try: |
| 277 |
obj, fmt, unboundop = _queues.get(self._id) |
| 278 |
except QueueEmpty as exc: |
| 279 |
if timeout is not None and time.time() >= end: |
| 280 |
raise # re-raise |
| 281 |
time.sleep(_delay) |
| 282 |
else: |
| 283 |
break |
| 284 |
if unboundop is not None: |
| 285 |
assert obj is None, repr(obj) |
| 286 |
return _resolve_unbound(unboundop) |
| 287 |
if fmt == _PICKLED: |
| 288 |
obj = pickle.loads(obj) |
| 289 |
else: |
| 290 |
assert fmt == _SHARED_ONLY |
| 291 |
return obj |
| 292 |
|
| 293 |
def get_nowait(self): |
| 294 |
"""Return the next object from the channel. |
| 295 |
|
| 296 |
If the queue is empty then raise QueueEmpty. Otherwise this |
| 297 |
is the same as get(). |
| 298 |
""" |
| 299 |
try: |
| 300 |
obj, fmt, unboundop = _queues.get(self._id) |
| 301 |
except QueueEmpty as exc: |
| 302 |
raise # re-raise |
| 303 |
if unboundop is not None: |
| 304 |
assert obj is None, repr(obj) |
| 305 |
return _resolve_unbound(unboundop) |
| 306 |
if fmt == _PICKLED: |
| 307 |
obj = pickle.loads(obj) |
| 308 |
else: |
| 309 |
assert fmt == _SHARED_ONLY |
| 310 |
return obj |
| 311 |
|
| 312 |
|
| 313 |
_queues._register_heap_types(Queue, QueueEmpty, QueueFull) |