table of Contents
@ (Using a queue to complete the inter-process communication)
1. Why use queue
It is between processes independent of each other, and the thread can share global variables
so if you want to talk inter-process data exchange
only through inter-process communication, such as socket. Too much trouble
here using the queue
Queue features: FIFO
2.python code implementation
import multiprocessing
def download_from_web(q):
"""下载数据"""
#模拟从网上下载数据
data = [11,22,33,44]
#向队列写入数据
for temp in data:
q.put(temp)
print("下载器已经下载完了数据并存入了队列中")
def analysis_data(q):
"""数据处理"""
waitting_analysis_data = list()
#从队列中获取数据
while True:
data = q.get()
waitting_analysis_data.append(data)
if q.empty():
break
print(waitting_analysis_data)
def main():
#1.创建一个队列
q = multiprocessing.Queue()
#创建多个进程,将队列的引用当做实参进行传递
p1 = multiprocessing.Process(target=download_from_web,args=(q,))
p2 = multiprocessing.Process(target=analysis_data,args=(q,))
p1.start()
p2.start()
if __name__ == '__main__':
main()