[英]How to dynamically change the value of variable in functions while using multiprocessing
how can i dynamically change the value of lis so that every second it'll output a list in which the last element is 2x the last element of the previous list.我如何动态更改 lis 的值,以便每秒 output 一个列表,其中最后一个元素是前一个列表最后一个元素的 2 倍。
import time, multiprocessing
lis = [1, 2, 4]
def printer():
while True:
print(lis)
time.sleep(1)
def updater():
while True:
time.sleep(1)
lis.append(lis[-1]*2)
if __name__ == '__main__':
process1 = multiprocessing.Process(target=updater)
process2 = multiprocessing.Process(target=printer)
process1.start()
process2.start()
process1.join()
process2.join()
i need the output to be something like this我需要 output 是这样的
[1, 2, 4]
[1, 2, 4, 8]
[1, 2, 4. 8. 16]
[1, 2, 4, 8, 16, 32]
.
.
but right now the output is但现在 output 是
[1, 2, 4]
[1, 2, 4]
[1, 2, 4]
[1, 2, 4]
.
.
I tried using global lis
but that didnt work either.我尝试使用global lis
,但也没有用。
You can achieve desired behavior using multiprocessing.Manager
.您可以使用multiprocessing.Manager
实现所需的行为。
Managers provide a way to create data which can be shared between different processes.管理器提供了一种创建可以在不同进程之间共享的数据的方法。 You can read more about it here .您可以在此处阅读更多相关信息。
Based on example from Server process section you can rewrite your code like this:基于服务器进程部分的示例,您可以像这样重写代码:
import time, multiprocessing
def printer(_lis):
while True:
print(_lis)
time.sleep(1)
def updater(_lis):
while True:
time.sleep(1)
_lis.append(_lis[-1]*2)
if __name__ == '__main__':
with multiprocessing.Manager() as manager:
lis = manager.list([1, 2, 4])
process1 = multiprocessing.Process(target=updater, args=(lis,))
process2 = multiprocessing.Process(target=printer, args=(lis,))
process1.start()
process2.start()
process1.join()
process2.join()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.