我正在编写一个我希望监控其状态的多处理过程。如何从thaht context访问my_var?
from multiprocessing import Process
import time
my_var = list()
def alter_my_var():
global my_var
for x in range(10):
my_var.append(x)
time.sleep(1)
p = Process(target=alter_my_var)
p.start()
while p.is_alive():
print "Length of my_var is %i" % len(my_var)
time.sleep(1)
p.join()
print "Done - final length of my_var is %s" % len(my_var)
由于
答案 0 :(得分:2)
您使用的是multiprocessing
而不是threading
。进程在不同的内存空间中运行,变量被复制到子进程,但它们不再指向相同的内存地址。因此,主进程无法读取您在进程中修改的内容。
如果您不关心某个流程或某个主题,请尝试按Process
更改Thread
,这样就可以了。
<强>输出强>:
Length of my_var is 0
Length of my_var is 1
Length of my_var is 2
Length of my_var is 3
Length of my_var is 4
Length of my_var is 6
Length of my_var is 7
Length of my_var is 8
Length of my_var is 9
Length of my_var is 10
Done - final length of my_var is 10
修改强>
正如其他人所说,如果你想继续使用一个过程,你必须建立某种IPC。您可以使用该队列,管理器等。
答案 1 :(得分:1)
使用Manager,每个进程都会获得列表的副本,因此您不会与 Manager()。list()共享一个对象:
from multiprocessing import Process, Manager
import time
my_var = Manager().list()
def alter_my_var(my_var):
for x in range(10):
my_var.append(x)
time.sleep(1)
p = Process(target=alter_my_var, args=(my_var, ))
p.start()
while p.is_alive():
print "Length of my_var is %i" % len(my_var)
time.sleep(1)
p.join()
print "Done - final length of my_var is %s" % len(my_var)
如果我们将代码粘贴到Ipython中,您可以看到输出:
## -- End pasted text --
Length of my_var is 0
Length of my_var is 1
Length of my_var is 3
Length of my_var is 4
Length of my_var is 5
Length of my_var is 6
Length of my_var is 7
Length of my_var is 8
Length of my_var is 9
Length of my_var is 10
Done - final length of my_var is 10
答案 2 :(得分:0)
试试这个:
from multiprocessing import Process, Pipe
import time
my_var = list()
def alter_my_var(my_var, conn):
for x in range(10):
my_var.append(x)
conn.send(len(my_var))
time.sleep(1)
global my_var
parent_conn, child_conn = Pipe()
p = Process(target=alter_my_var, args=(my_var,child_conn,))
p.start()
while p.is_alive():
myvar_len = parent_conn.recv()
print "Length of my_var is %i" % myvar_len
time.sleep(1)
p.join()
print "Done - final length of my_var is %s" % myvar_len