Why there is space in the code example in python threading

multithreading, python

Solution

If you examine the byte code for a print statement, it looks like this:

>>> def f():
...  print "Worker"
...
>>> dis.dis(f)
  2           0 LOAD_CONST               1 ('Worker')
              3 PRINT_ITEM
              4 PRINT_NEWLINE
              5 LOAD_CONST               0 (None)
              8 RETURN_VALUE

In fact, printing a number of items results in a number of PRINT_ITEM byte codes:

>>> def g():
...  print "Worker", "Hello"
...
>>> dis.dis(g)
  2           0 LOAD_CONST               1 ('Worker')
              3 PRINT_ITEM
              4 LOAD_CONST               2 ('Hello')
              7 PRINT_ITEM
              8 PRINT_NEWLINE
              9 LOAD_CONST               0 (None)
             12 RETURN_VALUE

To make multiple items have a space between them, the file object has a flag called softspace that indicates whether a space should be output before the next item. The code for PRINT_ITEM and PRINT_NEWLINE looks roughly like this:

def PRINT_ITEM(f, item):
    if f.softspace:
        f.write(' ')
    f.write(str(item))
    f.softspace = True

def PRINT_NEWLINE(f):
    f.write('\n')
    f.softspace = False

When you write to stdout from a number of threads at once, these operations become interleaved in random ways. So instead of getting PRINT_ITEM and PRINT_NEWLINE alternating, you can have two PRINT_ITEMs in a row. If that happens, you will have extra spaces in your output, because the two PRINT_ITEMs and the softspace flag will produce an extra space.

Problem

I am reading the PyMOTW threading post The first example: ``` import threading def worker(): """thread worker function""" print 'Worker' return threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) t.start() ``` I run it, and get the result: ``` Worker -Worker Worker -Worker Worker ``` The `-` is a `space`, and the format will be difference every time But I don't know why there is `space`? Some times it will output `empty line` also, why?

Original source