Python线程的工作原理

时间:2016-01-06 11:05:29

标签: python multithreading

代码如下所示:

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

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

1 个答案:

答案 0 :(得分:1)

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

感谢Vality的纠正。