我在挂起我的多线程函数的睡眠语句时遇到问题。我希望我的功能在程序的其余部分运行时继续它的业务。这是一个重现我的问题的玩具:
import multiprocessing, sys, time
def f(icount, _sleepTime = 1):
for i in range(icount):
time.sleep(_sleepTime)
print(_sleepTime)
def main(args):
m = multiprocessing.Process(target = f, args=(4, ))
m.run()
# f should be sleeping for 1 second so this print statement should come first
print(m.is_alive())
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
谁能解释为什么这段代码输出:
1
1
1
1
False
代替:
True
1
1
1
1
#
编辑
#
我最终想按计划运行此功能,并在执行该功能之前测试它是否正在运行。这是一个例子:
import multiprocessing, sys, time
def f(icount, _sleepTime = 1):
for i in range(icount):
time.sleep(_sleepTime)
print(_sleepTime)
def main(args):
m = multiprocessing.Process(target = f, args=(4, ))
for i in range(15):
time.sleep(.5)
if not m.is_alive():
# m.start throws an error after first run
m.run()
print("{}".format(m.is_alive()))
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))