do I need lock to protect mutli-thread race condition in my code
<p>Using Python 2.7 on Windows, and will use Jython which support true multi-threading. The method <code>sendMessage</code> is used to receive message from a specific client, and the client may send the same message to a few other clients (which is what parameter <code>receivers</code> is for, and <code>receivers</code> is a list). The method <code>receiveMessage</code> is used to receive message for a specific client, which are sent from other clients.</p>

<p>The question is whether I need any locks for method <code>sendMessage</code> and <code>receiveMessage</code>? I think there is no need, since even if a client X is receiving its message, it is perfect fine for another client Y to append to message pool to deliver message to client X. And I think for defaultdict/list, append/pop are both atomic and no need for protection.</p>

<p>Please feel free to correct me if I am wrong.</p>

<pre><code>from collections import defaultdict

class Foo:
    def __init__(self):
        # key: receiver client ID, value: message
        self.messagePool = defaultdict(list)
    def sendMessage(self, receivers, message):
        # check valid for receivers
        for r in receivers:
            self.messagePool[r].append(message)
    def receiveMessage(self, clientID):
        result = []
        while len(self.messagePool[clientID]) &gt; 0:
            result.append(self.messagePool[clientID].pop(0))

        return result
</code></pre>

<p>Race conditions is about two or more threads changing some global states at the same time.</p>

<p>In your code for <code>sendMessage</code>, you are changing <code>self.messagePool[r]</code>, which is a global object. Hence, <code>self.messagePool[r]</code> should be locked before appending a new item.</p>

<p>Same with your <code>receiveMessage</code> function.</p>

<p><code>list.append</code> and <code>list.pop</code> are armotized O(1) and O(1) operations, so it rarely would cause any race condition. However, the risk is still there.</p>

python multithreading python-2.7 jython