How Python Threading Works

The code is as follows:

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 did Thread 1 wake up before thread 0, while thread 0 was first?

+4
source share
1 answer

Python-Interpreter (CPython) , Thread - - GIL (https://wiki.python.org/moin/GlobalInterpreterLock). , , , thrads, - CPython , - . , , 2 .

Vality .

+1

Source: https://habr.com/ru/post/1623072/


All Articles