开发者

Python multiprocessing: no output with while-loop in worker function

开发者 https://www.devze.com 2023-01-28 04:15 出处:网络
I\'m exploring the Python multiprocessing module and don\'t understand why the following code does not print anything at all. Without the while-loop the program prints Worker_1 as expected.

I'm exploring the Python multiprocessing module and don't understand why the following code does not print anything at all. Without the while-loop the program prints Worker_1 as expected.

import multiprocessing, ti开发者_如何学运维me

def worker1():
    print 'Worker_1'
    while 1:
        print 'Worker_1'
        time.sleep(3)
    return

if __name__ == '__main__':
    jobs = []
    p = multiprocessing.Process(target=worker1)
    jobs.append(p)
    p.start()


On my system (Python 2.6&2.7 on Linux), this works as expected. Which platform are you using? On some platforms(Windows), fork hast to be emulated by creating a totally new process and setting it up. I suspect some stdout is not transferred to the child process. Try:

  • The threading module. It's sufficient if you just want to wait for an event in a thread.
  • Running your program on a POSIX-compatible platform, such as BSD, Linux or Solaris
  • Outputting to a file


Are you using IDLE? I think that this is the problem. The code you have works for me in Linux when called from the command line (it prints 'Worker_1' every 3 seconds). When I try it in IDLE, it stops immediately. This is because you don't have the p.join() in there which results in the main process stopping right away which then stops the worker process. Apparently, p.join() isn't as necessary from the command line in Linux though I would recommend it anyway.

However, even with p.join() and using IDLE, the script just sits there and we don't see any text. This is, I think, because of the weird way that IDLE reroutes stdout to idlelib.rpc.RPCProxy. So, in other words, if you are using IDLE, then that is your problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号