主循环旁的多处理 [英] Multiprocessing beside a main loop

查看:90
本文介绍了主循环旁的多处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个问题苦苦挣扎一段时间. 我正在构建一个使用主循环的小脚本.这是一个需要用户注意的过程.用户对这些步骤做出响应,然后使用某些功能会发生一些神奇的变化

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)

推荐答案

您应该这样做

mProcess = multiprocessing.Process(target=test)

代替

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

您的代码实际上在父进程中调用了test,并且该调用永不返回.

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

这篇关于主循环旁的多处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆