Docstring: Create a queue object with a given maximum size.If maxsize is <= 0, the queue size is infinite.
from queue import Queue
import randomq = Queue()print(q,type(q))# <queue.Queue object at 0x000001B6ED33DCA0> <class 'queue.Queue'>
q.put(random.randint(1,100))
q.put(random.randint(1,100))print(q)# <queue.Queue object at 0x00000184B2FA94C0>print(q.get())# 22print(q.get())# 83# print(q.get()) # it blocks if no item available# print(q.get(timeout=3)) # it blocks at most 'timeout' seconds and raises the Empty exception if no item was available within that time# print(q.get_nowait())# Remove and return an item from the queue without blocking.# Only get an item if one is immediately available. Otherwise raise the Empty exception.
q.maxsize =3
q.put(random.randint(1,100))
q.put(random.randint(1,100))
q.put(random.randint(1,100))# q.put(random.randint(1, 100), timeout=3) # Full# If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds # and raises the Full exception if no free slot was available within that time.
2、Queue & Threading – 1
import threading
import queue
import random
import timeq = queue.Queue()
q.put(random.randint(0,100))
q.put(random.randint(0,100))defq_put(q):time.sleep(3)q.put("I'm in function.")time.sleep(0.00001)print("=== function ===")print(q.get())print(q.get())t = threading.Thread(target=q_put, args=(q,))
t.start()print("=== After Threading ===")print(q.get(timeout=5))
5354=== After Threading ===
I'm in function.=== function ===
3、Queue & Threading – 2
import threading, queueq = queue.Queue()defworker():whileTrue:item = q.get()print(f'working on {item}')print(f'finished {item}')q.task_done()# turn on the worker thread
threading.Thread(target=worker, daemon=True).start()# send five task requests to the workerfor item inrange(5):q.put(item)# block until all tasks are done
q.join()print('all work completed')
working on 0
finished 0
working on 1
finished 1
working on 2
finished 2
working on 3
finished 3
working on 4
finished 4all work completed