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>You're looking for the <a href="https://docs.python.org/2/library/logging.html" rel="nofollow">logging</a> module:</p>

<blockquote>
  <p>15.7.9. Thread Safety</p>
  
  <p>The logging module is intended to be thread-safe without any special work needing to be done by its clients. It achieves this though using threading locks; there is one lock to serialize access to the moduleâs shared data, and each handler also creates a lock to serialize access to its underlying I/O.</p>
</blockquote>

<p>Here is an example:</p>

<pre><code>FORMAT = '%(threadName)s %(asctime)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG) # "level" default is to only print WARN and above.
logger = logging.getLogger('MyThreadClass')
logger.debug('')
</code></pre>

python multithreading