Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to make built-in containers (sets, dicts, lists) thread safe?
    text
    copied!<p>I understand <a href="https://stackoverflow.com/questions/2227169/are-python-built-in-containers-thread-safe">from this question</a> that if I want to have a <code>set</code> which is thread-safe I have to implement the thread-safety part on my own.</p> <p>Therefore I could come up with:</p> <pre><code>from threading import Lock class LockedSet(set): """A set where add() and remove() are thread-safe""" def __init__(self, *args, **kwargs): # Create a lock self._lock = Lock() # Call the original __init__ super(LockedSet, self).__init__(*args, **kwargs) def add(self, elem): self._lock.acquire() try: super(LockedSet, self).add(elem) finally: self._lock.release() def remove(self, elem): self._lock.acquire() try: super(LockedSet, self).remove(elem) finally: self._lock.release() </code></pre> <p>So, of course only add() and remove() are thread-safe in this implementation. The other methods are not because they were not overwritten in the subclass.</p> <p>Now, the pattern is pretty simple: acquire lock, call original method, release lock. If I follow the logic above, I would have to overwrite all methods exposed by <code>set</code> in essentially the same way, e.g.:</p> <p>(pseudo-code)</p> <pre><code>def &lt;method&gt;(&lt;args&gt;): 1. acquire lock 2. try: 3. call original method passing &lt;args&gt; 4. finally: 5. release lock </code></pre> <p>(/pseudo-code)</p> <p>This is not only tedious but also prone to errors. So, any ideas/suggestions on how to approach this in a better way?</p>
 

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