Python线程同时循环阻塞程序的其余部分?

2024-09-30 01:24:08 发布

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

也许我只是不明白线程在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循环上。在

有人知道发生了什么事吗?在


Tags: 代码selftruegoinitmaindef线程
1条回答
网友
1楼 · 发布于 2024-09-30 01:24:08

CPython有一个名为GIL全局解释器锁)的东西,它阻止两个线程同时执行。在

参见: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限制的,一次只执行一个线程。在线程之间以确定数量的操作码进行切换。买你的线程不会同时执行。在

如果希望同时执行,则应该查看multiprocessing模块

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

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

相关问题 更多 >

    热门问题