也许我只是不明白线程在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
(全局解释器锁)的东西,它阻止两个线程同时执行。在参见:https://wiki.python.org/moin/GlobalInterpreterLock
Python中的线程更适合IO绑定的任务,其中一个线程阻塞输入并允许其他线程执行。在
您尝试做的事情(以一种非常笨拙的方式)是受CPU限制的,一次只执行一个线程。在线程之间以确定数量的操作码进行切换。买你的线程不会同时执行。在
如果希望同时执行,则应该查看
multiprocessing
模块请参见:https://docs.python.org/3/library/multiprocessing.html
注意:在线程代码中,从主线程和第二线程执行相同的代码。两者都打印相同的字符串,因此很难识别解释器是否在线程之间切换
相关问题 更多 >
编程相关推荐