5

我在挂起我的多线程函数的睡眠语句时遇到问题。我希望我的功能在程序的其余部分运行时继续它的业务。这是一个重现我的问题的玩具:

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:]))
4

1 回答 1

8

使用startandjoin代替run

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.start()
    # f should be sleeping for 1 second so this print statement should come first
    print(m.is_alive())
    m.join()


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

#

编辑

#

同样,使用startandjoin代替run

import multiprocessing, sys, time

def f(icount, _sleepTime = 1):
    for i in range(icount):
        time.sleep(_sleepTime)
        print(_sleepTime)

def create_process():
    return multiprocessing.Process(target = f, args=(4, ))

def main(args):
    m = create_process()
    m.start()
    for i in range(15):
        time.sleep(.5)
        if not m.is_alive():
            # m.start throws an error after first run
            print("restarting")
            m.join()
            m = create_process()
            m.start()
        print("{}".format(m.is_alive()))
    m.join()


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
于 2012-10-02T15:49:34.427 回答