我创建了两个模块,其中有一些功能。我在 module1 中的单个函数中包含了 2 个函数,并在 module2 中导入了 module1,编译器中包含的函数 often1
似乎没有执行。
模块 1
import time,thread
def class_often():
while 1<2:
time.sleep(5)
print "Custom funtion not often runs."
def class_often1():
while 1<2:
time.sleep(2)
print "Custom funtion often runs."
def compiler():
class_often()
class_often1()
模块2
import time,d,thread
def often():
while 1<2:
time.sleep(2)
print "funtion not often runs."
def often1():
while 1<2:
time.sleep(2)
print "Function often runs."
thread.start_new_thread(often,())
thread.start_new_thread(often1,())
thread.start_new_thread(d.compiler,())
最佳答案
您在线程中启动编译器,但它调用 class_often
,它会阻塞,因为它是一个无限循环,因此无法调用第二个函数:
def compiler():
class_often() # blocks
class_often1()
您还需要在d.complier
中thread.start_new_thread
,即:
def class_often():
while True:
time.sleep(5)
print("Custom funtion not often runs.")
def class_often1():
while True:
time.sleep(2)
print("Custom funtion often runs.")
def compiler():
thread.start_new_thread(class_often,())
class_often1()
更改后将为您提供如下输出:
funtion not often runs.
Custom funtion often runs.
Function often runs.
Custom funtion not often runs.
funtion not often runs.
Custom funtion often runs.
Function often runs.
funtion not often runs.
Custom funtion often runs.
Function often runs.
funtion not often runs.
Custom funtion often runs.
Function often runs.
...........................
threading lib还建议使用 thread
库。
关于python - 线程处理时未执行的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33985365/