python线程.开始()在切换上下文之前没有运行到完成?

2024-04-19 16:52:34 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能解释一下Python线程是如何工作的吗?做线程.开始()在切换回另一个上下文(如下面的main)之前,不运行目标函数直到完成?你知道吗

import time
import threading

def threadfunc():
    # time.sleep(1)
    print('thread print 1', flush=True)
    print('thread print 2', flush=True)
    #time.sleep(1)

print('before thread', flush=True)

thread1 = threading.Thread(target=threadfunc)
thread1.start()

print('after thread', flush=True)

输出:

before thread
thread print 1
after thread
thread print 2 #shouldn't this be after "print 1"?

Tags: importtrue目标timemainsleep线程thread
1条回答
网友
1楼 · 发布于 2024-04-19 16:52:34

正如评论所解释的,线程或GIL在Python中不是这样工作的

CPython底层的许多C代码都会释放GIL,IO操作(如Solomon所说)来实现这一点,而一些库(例如NumPy)显式地释放它只是为了帮助多线程代码更快地运行

解释器还将尝试每隔few milliseconds切换线程

有关更多详细信息,请参见https://stackoverflow.com/a/49573860/1358308

相关问题 更多 >