Python threading with strange output errors
<p>I am new to threading in general and have been playing around with different ideas to get my feet under me. However, I came across something I am not sure how to explain. Here is the code:</p>

<pre><code>import threading, datetime
class ThreadClass(threading.Thread):
    def run(self):
        for _ in range(3):
            now = datetime.datetime.now()
            print "%s: %s" %(self.getName(), now)

for i in range(2):
    t = ThreadClass()
    t.start()
</code></pre>

<p>The program does exactly what I wanted it to do, however, the output has some random errors in it.</p>

<pre><code>Thread-1: 2016-10-12 17:34:23.012462
Thread-1: 2016-10-12 17:34:23.012802
 Thread-2: 2016-10-12 17:34:23.013025
Thread-2: 2016-10-12 17:34:23.013108

Thread-2: 2016-10-12 17:34:23.013225
Thread-1: 2016-10-12 17:34:23.013252
</code></pre>

<p>The errors are relatively consistent (i.e. the same space and new line show up in the output, just in different places). I suspect it has something to do with the threads trying to write to the output stream at about the same time, but in this particular run both errors occur when Thread-2 is running.</p>

<p>Any assistance in describe why this issue is occuring is greatly appreciated!</p>

<p>I am running this code with Python 2.7 on Ubuntu 14.04 (dual-core CPU), if that would make any difference.</p>

<p>Complement to Joseph's reply, you can use Semaphore</p>

<pre><code>from threading import Semaphore
writeLock = Semaphore(value = 1)
</code></pre>

<p>...</p>

<p>When you are about to print in the thread:</p>

<pre><code>writeLock.acquire()
print ("%s: %s" %(self.getName(), now))
writeLock.release()
</code></pre>

<p>writeLock makes sure only one thread can print at any single moment until release().</p>

<p>Image Semaphore as the conch in the "Lord of the flies", only the one who gets it can speak. When the first speaker finishes, he gives it to the next speaker.</p>

python multithreading