from multiprocessing import shared_memory
import time
a = shared_memory.ShareableList(['no'], name='123') # 创建共享内存,并且写值
count = 0
while True:
time.sleep(0.1)
count += 1
print(count)
if a[0] == 'yes':
break
if count >= 100:
break
a.shm.close()
a.shm.unlink()
update.py
from multiprocessing import shared_memory
a = shared_memory.ShareableList(name='123') # 更新共享内存
a[0] = 'yes'
参考: https://docs.python.org/3/library/multiprocessing.shared_memory.html
进程传递数据最简单方便的是通过Queue。这样你的自建类对象就可以放到队列中,由子进程获取。
到于Array, Var等方法,那是给高效数据共享用的。共享内存是进程通信的高级技巧。需要高性能计算的时候再研究这些方法。
Pool, Manager之类是一种封装。用得反而比较少。
python与C++共享内存里,还会使用一种Numpy中的数组。那个效率更高。
你的程序中子进程及传递参数都没有问题。你少了一句。在后面要加上
p.join()就可以了
如果不加,那么你的主进程不等子进程,它先退出了,往往操作系统会自动把子进程也杀掉。
另外子进程中的print输出有延时。即使你用sys.stdout.flush(),有时候它也会有延时。