Python:从父程序的并行进程中更新局部变量 [英] Python: Update Local Variable in a Parallel Process from Parent Program

查看:315
本文介绍了Python:从父程序的并行进程中更新局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编程还比较陌生,我要问的可能是不可能完成的任务.我想要做的是启动一个并行过程,该过程将持续运行,直到用户要求停止为止.进程启动后,我想从父程序更新并行进程内的局部变量之一,而无需停止进程.对于一个非常简单的示例,我要执行的并行过程如下:

I am relatively new to programming, and what I am asking might be a task that is not possible. What I want to do is start a parallel process, which will continuously run until requested to stop by the user. Once the process has started, I would like to update one of the local variables inside the parallel process from the parent program without stopping the process. For a very simple example, the parallel process I would like to execute would be the following:

import time

def loop(i):
    while 1:
        print i
        i+=1
        time.sleep(1)

连续不断地迭代和更新i.为了清楚起见,父程序将包含:

Which continuously iterates and updates i. For clarity the parent program will contain:

from multiprocessing import Process
from loop import loop

i = 1
p = Process(target = loop, args = (i))
p.start()

从父程序开始,一旦启动循环",我希望能够将输入"i"更改为另一个数字,并让循环在给定下一个起始值的情况下继续进行迭代.如果有人对如何执行此操作有任何想法,将不胜感激.

From the parent program, once "loop" has be initiated, I would like to be able to change the input "i" to another number and have loop continue to iterate given the next starting value. If anybody has any ideas on how to do this, it would be greatly appreciated.

推荐答案

您可以使用队列在进程之间传递数据:

You can use a queue to pass data between the processes:

from multiprocessing import Process, Queue
from loop import loop

i = 1
q = Queue()
q.put(i)
p = Process(target=loop, args=(q, ))
p.start()

每当您要将i的新值传递给其他过程时,只需输入 在队列中.

Whenever you want to transmit a new value of i to the other process, just put it in the queue.

相应地更改loop.py模块:

Change your loop.py module accordingly:

def loop(q):
  while True:
    i = q.get()
    print i

在您的主代码中,您可以为流程添加新值:

In your main code, you can put new values for the process:

while True:
  i+=1
  q.put(i)
  time.sleep(1)

这篇关于Python:从父程序的并行进程中更新局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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