进程间实现数据共享的三种方式
Posted apollo1616
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了进程间实现数据共享的三种方式相关的知识,希望对你有一定的参考价值。
1.Queue:
-linux:
q = multiprocessing.Queue()
def task(arg,q):
q.put(arg)
def run():
for i in range(10):
p = multiprocessing.Process(target=task, args=(i, q,))
p.start()
while True:
v = q.get()
print(v)
run()
-windows:
import multiprocessing
def task(arg,q):
q.put(arg)
if __name__ == '__main__':
q = multiprocessing.Queue()
for i in range(10):
p = multiprocessing.Process(target=task,args=(i,q,))
p.start()
while True:
v = q.get()
print(v)
2.Manager:(*)
-Linux:
m = multiprocessing.Manager()
dic = m.dict()
def task(arg):
dic[arg] = 100
def run():
for i in range(10):
p = multiprocessing.Process(target=task, args=(i,))
p.start()
input('>>>')
print(dic.values())
if __name__ == '__main__':
run()
-windows:
import time
import multiprocessing
def task(arg, dic):
time.sleep(2)
dic[arg] = 100
if __name__ == '__main__':
m = multiprocessing.Manager()
dic = m.dict()
process_list = []
for i in range(10):
p = multiprocessing.Process(target=task, args=(i, dic,))
p.start()
process_list.append(p)
while True:
count = 0
for p in process_list:
if not p.is_alive():
count += 1
if count == len(process_list):
break
print(dic)
3.其他电脑
def task(arg,dic):
pass
if __name__ == '__main__':
while True:
# 连接上指定的服务器
# 去机器上获取url
url = 'adfasdf'
p = multiprocessing.Process(target=task, args=(url,))
p.start()
以上是关于进程间实现数据共享的三种方式的主要内容,如果未能解决你的问题,请参考以下文章