posop
posop

Reputation: 531

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

Upvotes: 5

Views: 1591

Answers (1)

Oren
Oren

Reputation: 2807

Use start and join instead of 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:

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

Upvotes: 8

Related Questions