惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
A
About on SuperTechFans
博客园 - Franky
Engineering at Meta
Engineering at Meta
Recent Announcements
Recent Announcements
云风的 BLOG
云风的 BLOG
B
Blog
Microsoft Security Blog
Microsoft Security Blog
L
LangChain Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
U
Unit 42
Martin Fowler
Martin Fowler
Y
Y Combinator Blog
Stack Overflow Blog
Stack Overflow Blog
博客园 - 叶小钗
Vercel News
Vercel News
Apple Machine Learning Research
Apple Machine Learning Research
The Cloudflare Blog
Last Week in AI
Last Week in AI
腾讯CDC
Microsoft Azure Blog
Microsoft Azure Blog
爱范儿
爱范儿
V
V2EX
G
Google Developers Blog

博客园 - 北叶青藤

2096. Step-By-Step Directions From a Binary Tree Node to Another Find path from root to a target node in Binary Tree When Dijkstra Algorithm Should be Use? 1188. Design Bounded Blocking Queue 1115. Print FooBar Alternately 1114. Print in Order 1242. Web Crawler Multithreaded bot ip Log Rate Limiter Same Word of HTML Labels Most Frequent Call Chain remove prefix in a words list 1102. Path With Maximum Minimum Value Property Booking Optimizer minimum number 755. Pour Water Keyword Tagging in Reviews with Overlapping Matches Retryer Function Implementation 1125. Smallest Sufficient Team Print the terrain Split stay Task scheduling problem 滑雪问题 845. Longest Mountain in Array 723. Candy Crush 1539. Kth Missing Positive Number 1650. Lowest Common Ancestor of a Binary Tree III 424. Longest Repeating Character Replacement 843. Guess the Word 551. Student Attendance Record I
Python Multi-threading
北叶青藤 · 2026-07-13 · via 博客园 - 北叶青藤
import queue
import threading
import time

# Create a queue
q = queue.Queue()

def worker():
    while True:
        # Retrieve a task from the queue
        item = q.get()
        
        # None is our signal to stop the thread
        if item is None:
            q.task_done()
            break
            
        print(print(f"Working on {item}"))
        time.sleep(0.5) # Simulate work
        
        # Tell the queue that this specific item is fully processed
        q.task_done()

# Start worker threads
threads = []
for i in range(2):
    t = threading.Thread(target=worker)
    t.start()
    threads.append(t)

# Put items into the queue
for item in ["Task A", "Task B", "Task C"]:
    q.put(item)

# Block the main thread until all items are processed
q.join()
print("--- All tasks are finished! ---")

# Clean up threads by sending the stop signal (None)
for i in range(2):
    q.put(None)
for t in threads:
    t.join()

Common Pitfalls to Avoid

  • ValueError: task_done() called more times than put(): This happens if you accidentally call task_done() multiple times for a single get(), causing the internal counter to drop below zero.

Forgetting to call it: If a worker crashes or hits an early return/continue before calling task_done(), Queue.join() will wait forever because the counter will never hit zero.

Tip: Use a try...finally block in your worker to ensure q.task_done() is always called, even if an exception occurs during processing:

item = q.get()
try:
    # process item here
finally:
    q.task_done()

Producer-Consumer Pattern

import queue
import threading
import time
import random

# 1. Initialize a thread-safe queue
# Setting a maxsize prevents the producer from running away with memory
pipeline = queue.Queue(maxsize=5)

# A flag to signal workers to stop when production is completely done
STOP_SIGNAL = None

# 2. Define the Producer
def producer(q, num_items):
    print("[Producer]: Starting...")
    for i in range(1, num_items + 1):
        # Simulate time taken to generate or fetch data
        time.sleep(random.uniform(0.1, 0.4))
        item = f"Data-Package-{i}"
        
        # Put item into the queue (blocks if queue is full)
        q.put(item)
        print(f"[Producer]: Enqueued {item} (Queue size: {q.qsize()})")
        
    print("[Producer]: Done producing items.")

# 3. Define the Consumer
def consumer(q, consumer_id):
    print(f"[Consumer {consumer_id}]: Starting...")
    while True:
        # Get an item from the queue (blocks if queue is empty)
        item = q.get()
        
        # Check for the poison pill (stop signal)
        if item is STOP_SIGNAL:
            q.task_done()  # Acknowledge the stop signal task
            break
            
        # Simulate processing time
        print(f"[Consumer {consumer_id}]: Processing {item}...")
        time.sleep(random.uniform(0.3, 0.7)) 
        
        # Signal that the specific item is fully processed
        q.task_done()
        print(f"[Consumer {consumer_id}]: Finished {item}")
        
    print(f"[Consumer {consumer_id}]: Shutting down.")

# --- Main Execution ---
if __name__ == "__main__":
    num_consumers = 2
    total_items = 10
    
    # Create and start the producer thread
    producer_thread = threading.Thread(target=producer, args=(pipeline, total_items))
    producer_thread.start()
    
    # Create and start a pool of consumer threads
    consumer_threads = []
    for i in range(num_consumers):
        t = threading.Thread(target=consumer, args=(pipeline, i+1))
        t.start()
        consumer_threads.append(t)
        
    # Wait for the producer to finish generating all items
    producer_thread.join()
    
    # Wait for the queue to become completely empty and all tasks acknowledged
    pipeline.join()
    print("[Main]: All items in the queue have been successfully processed!")
    
    # Tell the consumers they can safely exit by sending "poison pills"
    for _ in range(num_consumers):
        pipeline.put(STOP_SIGNAL)
        
    # Wait for all consumer threads to completely shut down
    for t in consumer_threads:
        t.join()
        
    print("[Main]: Program finished cleanly.")