简体   繁体   English

time.sleep在python中挂起多线程函数

[英]time.sleep hangs multithread function in python

I am having trouble with a sleep statement hanging my multithreading function. 我在使用多线程函数挂起睡眠语句时遇到问题。 I want my function to go about it's buisness while the rest of the program runs. 我希望我的功能能够在程序的其余部分运行时实现它的功能。 Here is a toy that recreates my problem: 这是一个重现我的问题的玩具:

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

can anyone explain why this code outputs: 谁能解释为什么这段代码输出:

1
1
1
1
False

instead of: 代替:

True
1
1
1
1

#

EDIT 编辑

#

I eventually want to run this function on a schedual, and test if it is running before I execute the function. 我最终希望在调度上运行此函数,并在执行函数之前测试它是否正在运行。 This is an example: 这是一个例子:

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

Use start and join instead of run : 使用startjoin代替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:]))

#

EDIT 编辑

#

Again, use start and join instead of run : 再次,使用startjoin而不是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:]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM