gpt4 book ai didi

Python线程While循环阻塞了程序的其余部分?

转载 作者:太空宇宙 更新时间:2023-11-03 14:09:44 28 4
gpt4 key购买 nike

也许我只是不明白线程在Python中是如何工作的,但据我了解,下面的代码应该能够同时执行两个循环。

from threading import Thread

class minerThread(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
def startMining(self,mineFunc):
while True:
print "geg"


def Main():
go=1
miner=minerThread()
miner.start()
miner.startMining("addr")
while go>0:
print "mine"


#Enter main loop
if(__name__ == "__main__"):
Main()

但是,程序只是卡在线程的 startMining 循环上。

有谁知道这是怎么回事吗?

最佳答案

CPython 有一个名为 GIL (Global-Interpreter-Lock) 的东西,它可以防止 2 个线程同时执行。

参见:https://wiki.python.org/moin/GlobalInterpreterLock

In CPython, the global interpreter lock, or GIL, is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. This lock is necessary mainly because CPython's memory management is not thread-safe. (However, since the GIL exists, other features have grown to depend on the guarantees that it enforces.)

Python 中的线程更适合 IO 密集型任务,其中一个线程阻塞输入并允许其他线程执行。

您尝试做的事情(以一种非常尴尬的方式)是 CPU 限制的,并且一次只会执行一个线程。线程之间以确定数量的操作码进行切换。购买你的线程不会同时执行。

如果您想要同时执行,您应该查看多处理模块

参见:https://docs.python.org/3/library/multiprocessing.html

注意:在线程代码中,您从主线程和第二个线程执行相同的代码。两者都打印相同的字符串,因此您很难识别解释器是否在线程之间切换

关于Python线程While循环阻塞了程序的其余部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48594411/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com