Python线程的工作原理

代码如下所示:

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()

现在这段代码返回以下内容:

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

如何线程1在线程0之前醒来同时线程0是第一个进入?

最佳答案 最常见的Python-Interpreter(CPython)在一个Thread上运行,你创建的每个Thread都只是虚拟的,并且仍然在一个核心上执行 – 因为它是GIL( https://wiki.python.org/moin/GlobalInterpreterLock).执行它们的顺序不一定是启动thrads的顺序,这就是拥有线程的整个过程–CPython解释器将决定在任何给定时间执行哪个线程的哪一部分.由于您只能使用一个核心而线程只是虚拟的,因此您将无法在同一时间执行2个线程.

感谢Vality的纠正.

点赞