[英]Python, have a process run in the background and get status from the main thread
this is a noob question, I have never done much in Python. 这是一个菜鸟问题,我在Python中从未做过很多事。 I need to have a main process run and do stuff, while a background process does other calculations and saves the result to a variable.
我需要运行一个主进程并进行处理,而后台进程则进行其他计算并将结果保存到变量中。 When the main thread wants, it should be able to read the last value stored in the variable: every value stored before is forgotten.
当主线程需要时,它应该能够读取存储在变量中的最后一个值:之前存储的每个值都将被忘记。 Say that the background process is counting: I want to know what number it is at at this very moment.
说后台进程正在计数:我想知道此时此刻是多少。 Here's a dummy code:
这是一个伪代码:
from multiprocessing import Process, Pipe
import os
import time
def f(queue):
a=0
while True:
a=a+1
child_conn.send(a)
time.sleep(0.1)
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
time.sleep(1)
while True:
print(parent_conn.recv())
time.sleep(1)
So the main thread prints the variable of the background thread every second, which is updated 10 times a second. 因此,主线程每秒打印一次后台线程的变量,该变量每秒更新10次。 I have tried with Pipe and Queue, but I do not get the last stored variable.
我已经尝试过使用Pipe and Queue,但是没有得到最后存储的变量。 This output is 1,2,3,4,... while I want to get 10,20,30,... (or similar, depending on timing).
此输出是1,2,3,4,...,而我想得到10,20,30,...(或类似,取决于时间)。 The problem here is that it, as the name suggests, works as a queue.
这里的问题是,顾名思义,它像一个队列一样工作。
What I would do in java is create something like an asynctask and have it update a public variable, but my understanding is that multi processes cannot share variables. 我在Java中要做的是创建一个类似于asynctask的东西,并让它更新一个公共变量,但是我的理解是,多个进程无法共享变量。
What's the proper way of doing this with Python? 用Python执行此操作的正确方法是什么?
Use multiprocessing.Value , which is implemented with shared memory between the processes: 使用multiprocessing.Value ,它通过进程之间的共享内存实现:
from multiprocessing import Process, Value
import time
def f(n):
while True:
n.value += 1
time.sleep(0.1)
if __name__ == '__main__':
n = Value('i',0)
p = Process(target=f, args=(n,))
p.start()
while True:
time.sleep(1)
print(n.value)
Output: 输出:
7
17
26
35
44
53
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.