python queue
import multiprocessing
import time
if __name__ == '__main__':
queue = multiprocessing.Queue(3)
queue.put(1)
queue.put('hello')
queue.put([3,5])
if queue.qsize() == 0:
print('队列为空')
else:
print('队列不为空')
# 获取队列的个数
size = queue.qsize()
print(size)
# 获取数据
value = queue.get()
print(value,1111)
# 获取队列的个数
size = queue.qsize()
print(size, 2222)
# 获取数据
value = queue.get()
print(value, 1111)
# 获取队列的个数
size = queue.qsize()
print(size, 1111)
# 获取数据
value = queue.get()
print(value, 2222)
# 获取队列的个数
size = queue.qsize()
print(size, 2222)
# 获取数据
value = queue.get()
print(value, 3333)
# 获取队列的个数
size = queue.qsize()
print(size, 3333)
# 获取数据
value = queue.get()
print(value, 4444)
# 获取队列的个数
size = queue.qsize()
print(size, 4444)
打印结果:
队列不为空
3
1 1111
2 2222
hello 1111
1 1111
[3, 5] 2222
0 2222
python 消息队列Queue完成进程间通信
import multiprocessing
import time
# 写入数据
def write_data(queue):
for i in range(10):
if queue.full():
print('队列满了')
break
queue.put(i)
time.sleep(0.2)
print(i)
# 读取数据
def read_data(queue):
while True:
# 加入数据从队列取完了,那么跳出循环
if queue.qsize() == 0:
print('队列空了')
break
value = queue.get()
print(value)
if __name__ == '__main__':
# 创建消息队列
queue = multiprocessing.Queue(5)
# 创建写入数据的进程
write_process = multiprocessing.Process(target=write_data, args=(queue,))
# 创建读取数据的进程
read_process = multiprocessing.Process(target=read_data, args=(queue,))
# 启动进程
write_process.start()
# 主进程等待写入进程执行完成以后代码再继续往下执行
write_process.join()
read_process.start()
# 打印结果
0
1
2
3
4
队列满了
0
1
2
3
4
队列空了