简体   繁体   中英

Python multiprocessing closes too early

I'm trying to integrate multiprocessing into a project but I can't get it working. This is what I've got:

import time
import winsound
from multiprocessing import Process
winsound.MessageBeep()
def pr1():
    while 1:
        winsound.MessageBeep()
        time.sleep(0.5)
if __name__ == '__main__':
    p = Process(target=pr1, args=())
    p.start()
    p.join()

while 1:
    print('hey')

but if I run it i hear only one beep and i want it to repeat. How do I get this done?

oke plan b, I've got this now and I only get correct:

import time
import winsound
from multiprocessing import Process
def pr1():
    while 1:
        winsound.MessageBeep()
        print('its working') 
        time.sleep(0.5)
if __name__ == '__main__':
    print('correct')
    p = Process(target=pr1, args=())
    p.start()
    p.join()

while 1:
    print('hey')

So there is something wrong with with the creating of the process. Any ideas?

Indent the final

while 1:
    print('hey')

to make it part of the if -block

When starting the child process under Windows the module contents are first executed before the callable given as target is run. Because the module never finishes execution, this doesn't happen.

The second snippet as a whole then becomes:

import time
import winsound
from multiprocessing import Process
def pr1():
    while 1:
        winsound.MessageBeep()
        print('its working') 
        time.sleep(0.5)
if __name__ == '__main__':
    print('correct')
    p = Process(target=pr1, args=())
    p.start()
    p.join()

    while 1:
        print('hey')

To show the "its working" message you need to flush the buffer, because usually in processes the output is normally buffered.

import time
import winsound
from multiprocessing import Process
import sys
def pr1():
    while 1:
        winsound.MessageBeep()
        print('its working')
        time.sleep(0.5)
        sys.stdout.flush()
if __name__ == '__main__':
    print('correct')
    p = Process(target=pr1, args=())
    p.start()
    p.join()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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