队列的简单使用,队列先进先出
import queue # 不能用于多进程之间的通讯,可以用于多线程间的通讯 from multiprocessing import Queue # 可以用于进程之间的数据共享 q = Queue(3) # 创建一个队列对象,队列长度为3 q.put(1) q.put(2) q.put(3) # q.put(4) # 当队列已满,继续放值,,会阻塞程序 try: q.put_nowait(4) # 等同于 q.put(4, False) except: print("队列已经满了.") print(q.get()) print(q.get()) print(q.get()) # print(q.get()) # 当队列空了,继续取值,也会阻塞程序 try: q.get_nowait() # 等同于q.get(block=False) except: print("队列已经空了.")
执行结果:
队列已经满了. 1 2 3 队列已经空了.
队列的使用
from multiprocessing import Queue q = Queue(5) q.put("one") q.put("two") q.put("three") q.put("four") q.put("five") # q.put("six") # 队列的长度只有5,此时程序会阻塞在这里 print(q.get()) print(q.get()) print(q.get()) print(q.get()) print(q.get()) # print(q.get()) # 此时队列是空的,从空队列中拿数据也会阻塞
执行结果:
one
two
three
four
five