Multiprocessing beside a main loop

2019-08-04 04:37发布

问题:

I'm struggling with a issue for some time now. I'm building a little script which uses a main loop. This is a process that needs some attention from the users. The user responds on the steps and than some magic happens with use of some functions

Beside this I want to spawn another process which monitors the computer system for some specific events like pressing specif keys. If these events occur then it will launch the same functions as when the user gives in the right values.

So I need to make two processes: -The main loop (which allows user interaction) -The background "event scanner", which searches for specific events and then reacts on it.

I try this by launching a main loop and a daemon multiprocessing process. The problem is that when I launch the background process it starts, but after that I does not launch the main loop. I simplified everything a little to make it more clear:

import multiprocessing, sys, time

def main_loop():
    while 1:
        input = input('What kind of food do you like?')
        print(input)

def test():
    while 1:
        time.sleep(1)
        print('this should run in the background')

if __name__ == '__main__':
    try:
        print('hello!')
        mProcess = multiprocessing.Process(target=test())
        mProcess.daemon = True
        mProcess.start()
        #after starting main loop does not start while it prints out the test loop fine.
        main_loop() 
    except:
        sys.exit(0)

回答1:

You should do

mProcess = multiprocessing.Process(target=test)

instead of

mProcess = multiprocessing.Process(target=test())

Your code actually calls test in the parent process, and that call never returns.



回答2:

You can use the locking synchronization to have a better control over your program's flow. Curiously, the input function raise an EOF error, but I'm sure you can find a workaround.

import multiprocessing, sys, time

def main_loop(l):
    time.sleep(4)
    l.acquire()

    # raise an EOFError, I don't know why .
    #_input = input('What kind of food do you like?') 

    print(" raw input at 4 sec ")
    l.release()

    return

def test(l):
    i=0
    while i<8:
        time.sleep(1)

        l.acquire()
        print('this should run in the background : ', i+1,  'sec')
        l.release()

        i+=1

    return



if __name__ == '__main__':

    lock = multiprocessing.Lock()


    #try:
    print('hello!')
    mProcess = multiprocessing.Process(target=test, args = (lock, ) ).start()

    inputProcess = multiprocessing.Process(target=main_loop, args = (lock,)).start()



    #except:
        #sys.exit(0)