I was trying to learn python's threading and I found these result. I was wondering how python's print() actually outputs to the console.
import threading
import time
def testing(name):
print(name)
y = threading.Thread(target=testing, args=("y",))
y.start()
x = threading.Thread(target=testing, args=("x",))
x.start()
Output
yx
import threading
import time
def testing(name):
print(name)
y = threading.Thread(target=testing, args=("y",))
y.start()
time.sleep(.001)
x = threading.Thread(target=testing, args=("x",))
x.start()
Output
y
x
Really my question is why isn't the output of the first one:
y
x
CodePudding user response:
Note that print()
outputs your string, followed by a newline character (aka "\n").
I suspect that the print() function contains two calls to a lower-level C function (e.g. puts()) that handles the actual transfer of characters to stdout. The first puts()
transfers your string's characters, and then the second call transfers the implicit newline character.
When you run two threads at (almost) the same time, the second thread's print()
call may pre-empt the execution of the first thread's print()
call between those two lower-level calls, so that you get this order of execution:
Thread 1: puts("y")
Thread 2: puts("x")
Thread 2: puts("\n")
Thread 1: puts("\n")
.... which results in the string "yx\n\n" printed to stdout, as you saw.
Adding thetime.sleep()
to your main thread causes the execution of the second thread's print()
call to be delayed until after the first thread's print()
-call has finished:
Thread 1: puts("y")
Thread 1: puts("\n")
// ~1mS of time-delay passes
Thread 2: puts("x")
Thread 2: puts("\n")
... so in this scenario you get the output "y\nx\n" instead.