Reputation: 1314
Can someone explain how the Python threading works? Does thread.start() not run the target function to completion before switching back to another context like main below?
import time
import threading
def threadfunc():
# time.sleep(1)
print('thread print 1', flush=True)
print('thread print 2', flush=True)
#time.sleep(1)
print('before thread', flush=True)
thread1 = threading.Thread(target=threadfunc)
thread1.start()
print('after thread', flush=True)
Output:
before thread
thread print 1
after thread
thread print 2 #shouldn't this be after "print 1"?
Upvotes: 0
Views: 856
Reputation: 16214
as the comments explained, that's not how threads or the GIL work in Python
lots of the C code underlying CPython will release the GIL, IO operations (as Solomon noted) will do this, while some libraries (e.g. NumPy) explicitly release it just to help multithreaded code go faster
the interpreter will also try and switch threads every few milliseconds
see https://stackoverflow.com/a/49573860/1358308 for some more details
Upvotes: 2