From what I understood when doing research on the Python GIL, is that only one thread can be executed at the once (Whoever holds the lock). However, if that is true, then why would this code only take 3 seconds to execute, rather than 15 seconds?
import threading
import time
def worker():
"""thread worker function"""
time.sleep(3)
print 'Worker'
for i in range(5):
t = threading.Thread(target=worker)
t.start()
By intuition about threads, I would have thought this would take 3 seconds, which it does. However after learning about the GIL and that one thread can be executing at once, now I look at this code and think, why does it not take 15 seconds?
sleep()
does release the GIL. Also Python forces a thread switch every N millisecs or after executing M bytecode instructions (depending on which version of Python is being used). – Osterman