Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python线程的工作原理_Python_Multithreading - Fatal编程技术网

Python线程的工作原理

Python线程的工作原理,python,multithreading,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() 现在,此代码返回以下内容: thr

代码如下所示:

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解释器(CPython)在单个线程上运行,您创建的每个线程都是虚拟的,并且仍然在单个核心上执行,这是因为它是GIL()。执行它们的顺序不一定是启动thrads的顺序,这就是线程的全部意义——CPython解释器将决定在任何给定时间执行哪个线程的哪个部分。由于您只能使用一个内核,而线程只是虚拟的,因此您永远无法同时执行两个线程


感谢Vality的更正。

欢迎来到多线程世界,在这里,事情不会按顺序发生。这是线程的本质。它们同时执行,但当然不能同时打印。因此,在不同的线路上,唤醒似乎是无序的,但实际上,它们是在同一时间完成的……或者是接近“同一时间”的事情,因为实际的具体调度取决于OS/scheduler/CPU来制定和计划。除非你有10个内核,否则它们不可能在同一时间全部完成。@deceze是的,甚至线程的开始都是以微秒分隔的,因为Python是逐行执行的。很抱歉,这是错误的。Python确实使用多线程,只是最常见的实现CPython使用GIL(全局解释器锁)来确保Python解释器中一次只运行一个线程。然而,用C编写的python扩展可能会释放允许真正多线程的GIL。是的,你是正确的,我将相应地更新我的答案,但CPython主要与python一样被引用,因此我认为很明显我们讨论的是与OP相同的解释器,因为他没有提到任何具体的翻译。