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?
In fact, a Python process cannot run threads in parallel but it can run them concurrently through context switching during I/O bound operations. This limitation is actually enforced by GIL. The Python Global Interpreter Lock (GIL) prevents threads within the same process to be executed at the same time.
Threading in python is used to run multiple threads (tasks, function calls) at the same time. Note that this does not mean that they are executed on different CPUs. Python threads will NOT make your program faster if it already uses 100 % CPU time. In that case, you probably want to look into parallel programming.
The condition occurs when one thread tries to modify a shared resource at the same time that another thread is modifying that resource – this leads to garbled output, which is why threads need to be synchronized. The threading module of Python includes locks as a synchronization tool.
Python doesn't support multi-threading because Python on the Cpython interpreter does not support true multi-core execution via multithreading. However, Python does have a threading library. The GIL does not prevent threading.
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.
try using sys.stdout.write("Worker\n")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With