# -*- coding: utf-8 -*-
import copy
import random
from threading import Timer,current_thread
import queue
'''
queue 模块中 主要有 queue,simpleQueue,LifoQueue,PriorityQueue
queue first in first out,
Lifo Queue , Last in first out Queue
Priority Queue , the smaller number it is, the more priority it has
深浅拷贝:浅拷贝,object.copy(),copy.copy(object),开辟一块新的内存空间,这个内存空间存放指针指向被拷贝对象
深拷贝,copy.deepcopy(object) 开辟一块新的内存空间,这个内存空间存放与原有被拷贝对象一样的数据
'''
# def task(x):
# print(f"{x} is running")
# print(current_thread().name)
#
#
# if __name__ == '__main__':
# t=Timer(3,task,args=(10,))
# t.start()
# print('main')
# q= queue.Queue(3)
# for _ in range(3):
# q.put(_)
# for _ in range(3):
# print(q.get()) # 0 1 2
# q= queue.LifoQueue(3)
# for _ in range(3):
# q.put(_)
# for _ in range(3):
# print(q.get()) # 2 1 0
q= queue.PriorityQueue(3)
for _ in range(3):
q.put((random.choice(range(5)),_))
# q.put(tuple made as (priority,data))
# the smaller it is ,the quicker it out.
for _ in range(3):
print(q.get())
import queue
try:
q = queue.Queue(3) # 设置队列上限为3
q.put('python') # 在队列中插入字符串 'python'
q.put('-') # 在队列中插入字符串 '-'
q.put('100') # 在队列中插入字符串 '100'
for i in range(4): # 从队列中取数据,取出次数为4次,引发 queue.Empty 异常
print(q.get(block=False))
except queue.Empty:
print('queue.Empty')
import queue
try:
q = queue.Queue(3) # 设置队列上限为3
q.put('python') # 在队列中插入字符串 'python'
q.put('-') # 在队列中插入字符串 '-'
q.put('100') # 在队列中插入字符串 '100'
q.put('stay hungry, stay foolish', block=False) # 队列已满,继续往队列中放入数据,引发 queue.Full 异常
except queue.Full:
print('queue.Full')
import queue
try:
q = queue.Queue(2) # 设置队列上限为2
q.put_nowait('python') # 在队列中插入字符串 'python'
q.put_nowait('-') # 在队列中插入字符串 '-'
q.put_nowait('100') # 队列已满,继续在队列中插入字符串 '100',直接引发 queue.Full 异常
except queue.Full:
print('queue.Full')
import queue
try:
q = queue.Queue()
q.get(block = True, timeout = 5) # 队列为空,往队列中取数据时,等待5秒后会引发 queue.Empty 异常
except queue.Empty:
print('queue.Empty')
import queue
try:
q = queue.Queue()
q.get_nowait() # 队列为空,往队列中取数据时直接引发 queue.Empty 异常
except queue.Empty:
print('queue.Empty')
Queue 的用法
发布时间 2023-03-31 10:37:57作者: MrSphere