程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python realizes data sharing between processes through queues

編輯:Python

One 、 Third party libraries used

        multiprocessing ; os

Two 、 Data sharing between processes is not allowed by default , To achieve data sharing , Data sharing between processes can be achieved through queues .

import multiprocessing,os
def song(num,a,que):
# Print process number
print('song process :{}'.format(os.getpid()))
for i in range(num):
a=a+1
# Add data to the queue
que.put(a)
def dance(num,a,que):
# Print process number
print('dance process :{}'.format(os.getpid()))
while True:
# Take data out of the queue
a=que.get()
print(a)
# When the queue is empty que.empty()=True, End the operation of fetching data from the queue
if que.empty():
print(' End queue ')
break
def main():
a = 0
# Create a queue , Realize interprocess communication
que=multiprocessing.Queue(10)
# Instantiate two processes , And start the
#target Pointing function ,args Followed by parameters in tuple format , Pass it into the function as an actual parameter
multiprocessing.Process(target=song,args=(10,a,que)).start()
multiprocessing.Process(target=dance, args=(10,a,que)).start()
# Print process number
print(' The main process :{}'.format(os.getpid()))
que.close()
if __name__ =='__main__':
main()

Print the results :


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved