close

1. 基本操作 

blocking mode

import queue

q = queue.Queue()

# Put something in
q.put({"type": "PRINT", "payload": "Hello"})

# Get it back (blocking by default)
item = q.get()
print(item)   # {'type': 'PRINT', 'payload': 'Hello'}

# Tell the queue we're done with this item
q.task_done()

2. Non-blocking or timeout

import queue

q = queue.Queue()

# Put something in
q.put({"type": "PRINT", "payload": "Hello"})

# Get it back (blocking by default)
item = q.get()
print(item)   # {'type': 'PRINT', 'payload': 'Hello'}

try:
    item = q.get(timeout=2)   # wait up to 2 second
    print(item)
except queue.Empty:
    print("No item available")


# Tell the queue we're done with this item
q.task_done()

3. Inspect without removing

# Put something in
q.put({"type": "PRINT", "payload": "Hello"})

# Get it back (blocking by default)
print("Queue size:", q.qsize())
print("Is empty?", q.empty())
print("Is full?", q.full())

Queue size: 1
Is empty? False
Is full? False

# Put something in
q.put({"type": "PRINT"})
q.put({"name": "Ryan"})

# Get it back (blocking by default)
print("Queue size:", q.qsize())
print("Is empty?", q.empty())
print("Is full?", q.full())

Queue size: 2
Is empty? False
Is full? False

 5. Wait for all tasks to finish

If you’re using worker threads:

q.join() # blocks until every put() item has a matching task_done()

 

 結論:

  • q.put(item) → enqueue.

  • q.get() → dequeue.

  • process it.

  • q.task_done() → tell the queue it’s handled.

  • q.join() → optionally wait until all enqueued items are handled.

 

 

 

 

 

 

 

 

 

 

全站熱搜
創作者介紹
創作者 me1237guy 的頭像
me1237guy

天天向上

me1237guy 發表在 痞客邦 留言(0) 人氣()