Reputation: 61
The code looks like this :
import time
from threading import Thread
def sleeper(i):
print "thread %d sleeps for 5 seconds" % i
time.sleep(5)
print "thread %d woke up" % i
for i in range(10):
t = Thread(target=sleeper, args=(i,))
t.start()
Now this code returns the following :
thread 0 sleeps for 5 seconds
thread 1 sleeps for 5 seconds
thread 2 sleeps for 5 seconds
thread 3 sleeps for 5 seconds
thread 4 sleeps for 5 seconds
thread 5 sleeps for 5 seconds
thread 6 sleeps for 5 seconds
thread 7 sleeps for 5 seconds
thread 8 sleeps for 5 seconds
thread 9 sleeps for 5 seconds
thread 1 woke up
thread 0 woke up
thread 3 woke up
thread 2 woke up
thread 5 woke up
thread 9 woke up
thread 8 woke up
thread 7 woke up
thread 6 woke up
thread 4 woke up
How Thread 1 wokeup before thread 0 meanwhile thread 0 was the first to enter ?
Upvotes: 4
Views: 99
Reputation: 8435
The most common Python-Interpreter (CPython) runs on a single Thread, every Thread you create is just virtual and is still executed on a single core - due to it's GIL (https://wiki.python.org/moin/GlobalInterpreterLock). The order in which they are executed doesn't have to be necessarily the order in which you start the thrads, that's the entire point of having threads - the CPython interpreter will decide which part of which thread is to be executed by any given time. Since you can only use one core and threads are just virtual, you'll never be able to execute 2 threads at the exact same time.
Thanks to Vality for the correction.
Upvotes: 1