Python中两个多进程之间的共享列表



我正在学习如何在Python中使用multiprocessing模块,并根据在线教程试用我自己的代码。这是我的代码

import multiprocessing as mp
import time
manager = mp.Manager()
def update_array_list(datalist):
for i in range(1,10):
datalist.append(i)
print(f"loading list array with {i} elements : {datalist}")
print("_________________________________________")
time.sleep(2)
def display_array_list(datalist):
while True:
print(f"Items in array {datalist} ")
time.sleep(1)
if __name__ == '__main__':   
datalist = manager.list()
datalist.clear()
l1 = mp.Process(target=update_array_list,args=(datalist))
l2 = mp.Process(target=display_array_list,args=(datalist))
l1.start()
l2.start()
l1.join()
l2.join()

我的l1进程每隔两秒更新共享列表datalist,而我的l2进程每隔1秒打印它们。

我的代码没有运行,尽管这与教程几乎相同。

我得到以下错误。

...............
_check_not_importing_main()
File "C:UserspgoonetiAnaconda3envsNOUSlibmultiprocessingspawn.py", line 136, in _check_not_importing_main
is not going to be frozen to produce an executable.''')
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.

这里的错误是什么?

在ms windows和macOS上,multiprocessing附带了一些额外的编程指南。

由于multiprocessing必须在这些平台上工作,您的脚本必须可安全导入。这意味着在if __name__ == "__main__":块之外,理想情况下应该只有导入、函数和类定义。

当然,您不应该尝试实例化该块之外的任何multiprocessing.Processmultiprocessing.Poolmultiprocessing.Manager类!

考虑在"__main__"块之外创建Process时会发生什么:

  1. 您可以启动运行脚本的Python
  2. 您启动Process
  3. Python启动了一个新的Python解释器,用于导入您的脚本
  4. 返回步骤2

如果不选中,这将用Python进程填满机器的内存。因此CCD_ 14。

您的代码是可以的,只需注意文档,因为参数应该是元组,而不是列表((

尝试更改以下行(注意参数后的逗号(:

l1 = mp.Process(target=update_array_list,args=(datalist,))
l2 = mp.Process(target=display_array_list,args=(datalist,))
$ python3 multi.py
loading list array with 1 elements : [1]
_________________________________________
Items in array [1] 
Items in array [1] 
Items in array [1, 2] 
loading list array with 2 elements : [1, 2]
_________________________________________
Items in array [1, 2] 
Items in array [1, 2, 3] 
loading list array with 3 elements : [1, 2, 3]
_________________________________________
Items in array [1, 2, 3] 
Items in array [1, 2, 3, 4] 
loading list array with 4 elements : [1, 2, 3, 4]
_________________________________________
Items in array [1, 2, 3, 4] 
Items in array [1, 2, 3, 4] 
loading list array with 5 elements : [1, 2, 3, 4, 5]
_________________________________________

相关内容

  • 没有找到相关文章

最新更新