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

推荐订阅源

S
Schneier on Security
博客园_首页
量子位
博客园 - 司徒正美
S
SegmentFault 最新的问题
J
Java Code Geeks
小众软件
小众软件
博客园 - 【当耐特】
The Register - Security
The Register - Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Microsoft Azure Blog
Microsoft Azure Blog
G
Google Developers Blog
Blog — PlanetScale
Blog — PlanetScale
T
Tailwind CSS Blog
博客园 - Franky
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
G
GRAHAM CLULEY
Cyberwarzone
Cyberwarzone
腾讯CDC
Apple Machine Learning Research
Apple Machine Learning Research
V
Visual Studio Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Hacker News
The Hacker News
aimingoo的专栏
aimingoo的专栏
V
Vulnerabilities – Threatpost
P
Palo Alto Networks Blog
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
F
Full Disclosure
D
DataBreaches.Net
Martin Fowler
Martin Fowler
Cisco Talos Blog
Cisco Talos Blog
L
LINUX DO - 最新话题
云风的 BLOG
云风的 BLOG
C
Check Point Blog
T
Threatpost
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
W
WeLiveSecurity
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
有赞技术团队
有赞技术团队
Hugging Face - Blog
Hugging Face - Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
L
Lohrmann on Cybersecurity
Last Week in AI
Last Week in AI
T
Tor Project blog
T
Troy Hunt's Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
Security Affairs
SecWiki News
SecWiki News

博客园 - 北叶青藤

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.")