0x03 共享变量
共享变量
多进程中的每个进程与多线程中不同, 是不会共享变量的, 所使用的变量每个进程都会独自拷贝一份, 如果使用共享变量, 直接使用Python中的对象是不可行的:
import os
from multiprocessing import Process
vip_list = []
def testFunc(cc):
vip_list.append(cc)
print('process id:', os.getpid())
if __name__ == '__main__':
threads = []
for ll in range(10):
t = Process(target=testFunc, args=(ll,))
t.daemon = True
threads.append(t)
for i in range(len(threads)):
threads[i].start()
for j in range(len(threads)):
threads[j].join()
print("------------------------")
print('process id:', os.getpid())
print(vip_list)输出的结果为:
可以看到, 我们想让所有的进程把结果都存入到vip_list中, 但是每个进程都不会把结果存进去, 仍然是一个空列表. 这是因为vip_list列表不是一个共享变量, 不能被子进程使用.
可以使用multiprocessing包自带的共享变量类来实现. 其中的Value, Array以及Manager类都可以作为共享变量, 被多个进程共享使用.
Value: 共享数值
Array共享列表
结果为:
Manager: 支持多种形式,
list,dict等Python对象以及Value,Array和Queue,Event,Lock等并行同步工具. 只需要调用Manager对象对应的属性.```python import os from multiprocessing import Process, Manager, Lock
lock = Lock() manager = Manager() sum = manager.Value('tmp', 0)
def testFunc(cc, lock): with lock: sum.value += cc
if name == 'main': threads = []
```
参考资料
最后更新于
这有帮助吗?