Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a relatively simple approach (ignores exceptions, attribute-access, special methods, etc):</p> <pre><code>import Queue import threading def serialize(q): """runs a serializer on queue q: put [-1]*4 on q to terminate.""" while True: # get output-queue for result, a callable, its args and kwds out_q, tocall, args, kwds = q.get() if out_q == -1: return result = tocall(*args, **kwds) out_q.put(result) class WrapCall(object): """Wraps a callable to serialize calls to it.""" def __init__(self, inq, ouq, tocall): self.inq = inq self.ouq = ouq self.tocall = tocall def __call__(self, *a, **k): self.inq.put((self.ouq, self.tocall, a, k)) if self.ouq is None: return None return self.ouq.get() class WrapObj(object): """Wraps any object to serialize all calls to its methods.""" def __init__(self, obj): self._o = obj self._q = Queue.Queue() t = threading.Thread(target=serialize, args=(self._q,)) t.setDaemon(True) t.start() self.t = t def __getattr__(self, n): """Wraps methods of self.w into an appropriate WrapCall instance.""" towrap = getattr(self._o, n) if not callable(towrap): raise TypeError('Cannot wrap noncallable attribute %r (type: %s)' % (n, type(towrap))) q = Queue.Queue() return WrapCall(self._q, q, towrap) def WrapperWait(self): """Return only when self.t has served all pending requests.""" q = Queue.Queue() w = WrapCall(self.__q, q, lambda: None) return w() </code></pre> <p>With this "serializer", you can do</p> <pre><code>myobj = WrapObj(Command()) </code></pre> <p>and now all calls to myobj's (non-special) methods are serialized in a thread-safe way.</p> <p>For your specific case, where there's only one method on the object, you could simplify this a bit further, but this is an already-simplified version of something I wrote and use often (supporting attribute getting and setting, special methods, etc, is a tad too complex to be worth it; the complete version does support catching and reraising exceptions raised in the wrapper object's methods, an optimization for calls whose results or exceptions you don't care about, and a few more tweaks, but not serialization of attributes and special methods).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload