今天干活之队列操作,关于队列里面函数的用法就不一一列举了。来代码实例化。
from multiprocessing import Process
from multiprocessing import Queue
import time
import random
#需求:
#在父进程当中创建两个子进程,一个往Queue里写数据,一个从Queue里读取数据:
#写操作
def write(q):
# 由于进程之间的通信只能通过队列来完成,
# 所以队列中最后一个元素"Exit"为退出读取进程的标志
for value in [‘A’,‘B’,‘C’,‘D’,‘Exit’]:
print(‘Put %s from Queue’%(value))
q.put(value)
time.sleep(random.random())
#读操作
def read(q):
print(‘我要从队列当中读取数据了~’)
while True:
if not q.empty():
value = q.get()
if value == ‘Exit’:
print(‘Get %s from Queue’ % (value))
print(‘所有读写进程结束’)
break
else:
print(‘Get %s from Queue’%(value))
time.sleep(random.random())
if name == ‘main’:
#创建一个队列
q = Queue()
#创建两个进程
pw = Process(target=write,args=(q,))
pr = Process(target=read,args=(q,))
#启动
pw.start()# 写入
pr.start()# 读取
print(‘所有读写进程开始’)
# 运行结果
‘’’
所有读写进程开始
Put A from Queue
我要从队列当中读取数据了~
Get A from Queue
Put B from Queue
Get B from Queue
Put C from Queue
Get C from Queue
Put D from Queue
Get D from Queue
Put Exit from Queue
Get Exit from Queue
所有读写进程结束
‘’’
补充课堂笔记
python队列操作实例

相关文章:

  • 2021-08-29
  • 2021-09-10
  • 2022-01-11
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-30
  • 2021-12-18
  • 2022-12-23
  • 2022-12-23
  • 2021-11-14
相关资源
相似解决方案