使用global + 进程锁是无法对数据进行修改的,只能查看数据。
- 代码如下:
import multiprocessing x = 0 lock = multiprocessing.Lock() def main(): global x lock.acquire() x += 1 lock.release() if __name__ == '__main__': pool = multiprocessing.Pool(4) for i in range(4): pool.apply_async(main) pool.close() pool.join() print(x) # 输出0 并未对数据进行更改 print("end")
查了半天资料,并未发现 进程池数据共享,执行以下代码:
import multiprocessing def main(num): num.value += 1 if __name__ == '__main__': num = multiprocessing.Value("d", 10.0) pool = multiprocessing.Pool(4) for i in range(4): pool.apply_async(main, args=(num,)) pool.close() pool.join() print(num.value) # 值仍为10.0,并未改变 print("end")
要实现进程数据共享,就需要放弃进程池。。
如果有方法,请告诉我!
使用多进程进行数据共享
import multiprocessing def main(v): v.value += 1 if __name__ == '__main__': value = multiprocessing.Value("d", 10.0) jobs = [multiprocessing.Process(target=main, args=(value,)) for i in range(10)] for j in jobs: j.start() for j in jobs: j.join() print('Results:', value.value) # result 20.0 修改成功