当函数在另一个模块中时线程无法正常工作
Threading not working properly when function is in another module
我目前在 Python 中使用守护线程来不断检测后台屏幕的某些部分,而其他更重要的功能正在 运行 中。 testImToStr
与我正在使用的其余代码位于同一个文件中。
def testImToStr():
while True:
pospro.imagetoString();
doImageToString = threading.Thread(target=testImToStr, args=(), daemon=True)
doImageToString.start()
while True:
#other stuff i was too lazy to copy over
这个版本可以正常工作,因为它在 while 循环中同时进行图像处理和其他工作。
但是,目标线程在另一个模块中:
doImageToString = threading.Thread(target=pospro.loopedImToStr, args=(), daemon=True)
doImageToString.start()
while True:
#other stuff i was too lazy to copy over
其他模块:
def loopedImToStr():
while True:
imagetoString()
def imagetoString():
#stuff here
它只循环目标线程,而不是 运行 最初创建线程的文件中的 while 循环。当线程与循环在同一个文件中时,两个循环都是 运行,而当它们在不同的文件中时,只有线程是 运行,这是怎么回事?
我认为你所有的问题都犯了最常见的错误 - target
必须是没有 ()
的函数名称 - 所谓的 callback
Thread(target=pospro.loopedImToStr, daemon=True)
以后Thread.start()
会用()
到运行。
在您的代码中,您 运行 testImToStr()
立即喜欢
result = testImToStr()
doImageToString = threading.Thread(target=result, ...)
所以 testImToStr()
阻止所有代码并且它不能 运行 其他循环。
我目前在 Python 中使用守护线程来不断检测后台屏幕的某些部分,而其他更重要的功能正在 运行 中。 testImToStr
与我正在使用的其余代码位于同一个文件中。
def testImToStr():
while True:
pospro.imagetoString();
doImageToString = threading.Thread(target=testImToStr, args=(), daemon=True)
doImageToString.start()
while True:
#other stuff i was too lazy to copy over
这个版本可以正常工作,因为它在 while 循环中同时进行图像处理和其他工作。 但是,目标线程在另一个模块中:
doImageToString = threading.Thread(target=pospro.loopedImToStr, args=(), daemon=True)
doImageToString.start()
while True:
#other stuff i was too lazy to copy over
其他模块:
def loopedImToStr():
while True:
imagetoString()
def imagetoString():
#stuff here
它只循环目标线程,而不是 运行 最初创建线程的文件中的 while 循环。当线程与循环在同一个文件中时,两个循环都是 运行,而当它们在不同的文件中时,只有线程是 运行,这是怎么回事?
我认为你所有的问题都犯了最常见的错误 - target
必须是没有 ()
的函数名称 - 所谓的 callback
Thread(target=pospro.loopedImToStr, daemon=True)
以后Thread.start()
会用()
到运行。
在您的代码中,您 运行 testImToStr()
立即喜欢
result = testImToStr()
doImageToString = threading.Thread(target=result, ...)
所以 testImToStr()
阻止所有代码并且它不能 运行 其他循环。