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

推荐订阅源

博客园 - 聂微东
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
L
LangChain Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
WordPress大学
WordPress大学
T
The Blog of Author Tim Ferriss
Blog — PlanetScale
Blog — PlanetScale
J
Java Code Geeks
Y
Y Combinator Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
GbyAI
GbyAI
Vercel News
Vercel News
大猫的无限游戏
大猫的无限游戏
T
Tailwind CSS Blog
Jina AI
Jina AI
B
Blog
Recorded Future
Recorded Future
MyScale Blog
MyScale Blog
I
InfoQ
aimingoo的专栏
aimingoo的专栏
博客园_首页
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Cloudflare Blog
雷峰网
雷峰网
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
腾讯CDC
爱范儿
爱范儿
Last Week in AI
Last Week in AI
博客园 - 三生石上(FineUI控件)
博客园 - Franky
Schneier on Security
Schneier on Security
V
V2EX
TaoSecurity Blog
TaoSecurity Blog
H
Hacker News: Front Page
Cloudbric
Cloudbric
D
DataBreaches.Net
B
Blog RSS Feed
P
Palo Alto Networks Blog
云风的 BLOG
云风的 BLOG
NISL@THU
NISL@THU
I
Intezer
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Cyberwarzone
Cyberwarzone
F
Fortinet All Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cybersecurity and Infrastructure Security Agency CISA
C
Cisco Blogs
K
Kaspersky official blog
Forbes - Security
Forbes - Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Mastering Concurrency with the Sleeping Barber Problem
Brandon Kindred · 2026-06-13 · via DEV Community

Mastering Concurrency with the Sleeping Barber Problem

Hey there, fellow coder! Today, we're diving into one of the most fascinating concepts in computer science: the Sleeping Barber Problem. Whether you’re just getting into concurrency or you’re curious about how resource management works in real-world systems, this problem is a great way to get your feet wet.

In this post, we’ll break down what the Sleeping Barber Problem is, the key concepts it demonstrates, and how you can use Python to solve it. Plus, we’ll explore how you can apply these concepts to real-world programming problems.

What Is the Sleeping Barber Problem and Why Does It Matter?

The Sleeping Barber Problem is a classic scenario in computer science that models resource management and synchronization in a multi-threaded system. Imagine a barber shop with one barber, a single barber chair, and a waiting room with a limited number of chairs. Here’s how it works:

  • When no customers are present, the barber falls asleep in the chair, waiting for someone to arrive.

  • When a customer comes in and finds the barber asleep, they wake the barber up and sit down to get a haircut.

  • If the barber is already busy cutting hair, the customer either waits in the waiting room if there are empty chairs, or leaves if all the chairs are taken.

  • When the barber finishes cutting one customer’s hair, they check if there are other customers waiting. If there are, the barber invites the next customer to sit down for a haircut. If no one is waiting, the barber goes back to sleep.

Now, you might be wondering, “Why does this problem matter in programming?” Well, it turns out this simple scenario mimics real-world challenges that occur in concurrent programming — where multiple tasks (in this case, customers) compete for a limited resource (the barber). Understanding the Sleeping Barber Problem helps us grasp core concepts that we encounter when writing multi-threaded or multi-process applications.

Concurrency

The first key idea demonstrated by the Sleeping Barber Problem is concurrency — the ability of a system to handle multiple tasks at once. In the context of our barber shop, concurrency means handling multiple customers arriving at random times, possibly when the barber is busy with someone else. The barber can’t serve two customers simultaneously, so they must deal with the arriving customers in some orderly fashion.

In real-world applications, concurrency is critical. Think about a web server handling multiple user requests. The server is like the barber: it can process only one request at a time, but many requests may come in at once. Concurrency is what allows the server to juggle all those requests efficiently. Without managing concurrency properly, requests (like customers) might be dropped or left waiting indefinitely, leading to poor system performance or failure.

Synchronization

While concurrency deals with running multiple tasks, synchronization ensures that these tasks work together without interfering with each other. In the barber shop, synchronization guarantees that no two customers can sit in the barber’s chair at the same time or occupy the same waiting room chair. We use synchronization mechanisms (like locks and condition variables) to ensure that access to shared resources (the barber’s chair and waiting room chairs) is controlled.

In programming, synchronization is essential to avoid problems like race conditions, where two threads try to modify the same data at the same time. For example, if two customers both try to sit in the barber chair simultaneously, chaos would ensue. Similarly, in a multi-threaded application, if two threads try to update a shared variable without proper synchronization, they could overwrite each other’s changes, leading to bugs and unpredictable behavior.

Resource Allocation

The next concept is resource allocation where we figure out how to distribute limited resources among multiple tasks. In the barber shop, the barber chair and the waiting room chairs are limited resources. If all the waiting room chairs are occupied, new customers will have to leave. This models what happens in many real-world systems: you have a finite amount of memory, CPU power, or network bandwidth, and you have to figure out how to allocate those resources fairly and efficiently.

In real-world programming, resource allocation comes up in scenarios like thread pools. A thread pool is a group of worker threads that can execute tasks. When the pool is full (like the waiting room chairs), new tasks either have to wait or be rejected. Efficient resource allocation ensures that your system doesn’t become overloaded, and tasks are handled in an orderly way.

Blocking and Waiting

Another key part of the Sleeping Barber Problem is the idea of blocking and waiting. When the barber has no customers, they “block” or “wait” by falling asleep until a customer wakes them up. Similarly, if a customer arrives when the barber is busy, they “wait” in the waiting room for their turn. In programming, blocking refers to a task that can’t proceed until some condition is met — such as waiting for a file to become available or waiting for data to be written to a database.

Blocking and waiting are crucial for managing system resources efficiently. For example, in a database, if a process tries to access a record that another process is modifying, it may have to wait (block) until the record is available. Similarly, a customer waiting for the barber to finish a haircut is analogous to one process waiting for another to release a resource.

The Sleeping Barber Problem in Python

Now that we’ve talked about the concepts, let’s see them in action with a Python implementation. This example uses threading to simulate the barber and customers.

import threading
import time
import random
class BarberShop:
    def __init__(self, num_chairs, total_customers):
        self.num_chairs = num_chairs
        self.total_customers = total_customers
        self.customers_served = 0
        self.waiting_customers = 0
        self.shop_open = True
        self.barber_ready = threading.Condition()
        self.customer_ready = threading.Condition()
    def open_shop(self):
        print("The barber shop is now open.")
        barber_thread = threading.Thread(target=self.barber)
        barber_thread.start()
    def barber(self):
        while True:
            with self.customer_ready:
                while self.waiting_customers == 0:
                    if not self.shop_open:
                        print("The barber shop is closing. No more customers.")
                        return  # Exit when shop is closed and no customers remain
                    print("The barber is sleeping...")
                    self.customer_ready.wait()  # Wait for a customer to arrive
                # A customer is ready for a haircut
                self.waiting_customers -= 1
                print("The barber starts cutting hair.")
            # Simulate hair cutting
            time.sleep(random.randint(1, 3))
            with self.barber_ready:
                self.barber_ready.notify()  # Notify a customer that the barber is done
                print("The barber finished cutting hair.")

            with self.customer_ready:
                self.customers_served += 1
                if self.customers_served == self.total_customers:
                    self.shop_open = False  # Close the shop when all customers are served
    def customer(self, customer_id):
        with self.customer_ready:
            if self.waiting_customers < self.num_chairs:
                self.waiting_customers += 1
                print(f"Customer {customer_id} is waiting. Total waiting customers: {self.waiting_customers}")
                self.customer_ready.notify()  # Notify the barber that a customer is ready
            else:
                print(f"Customer {customer_id} left as there are no free chairs.")
                return  # Customer leaves if no chair is available
        # Wait for the barber to be ready
        with self.barber_ready:
            self.barber_ready.wait()  # Wait until the barber is ready
            print(f"Customer {customer_id} is getting a haircut.")
def main():
    num_chairs = 3  # Number of waiting chairs in the barber shop
    total_customers = 10  # Total number of customers to be served
    barber_shop = BarberShop(num_chairs, total_customers)
    barber_shop.open_shop()
    # Simulate customers arriving at random intervals
    for customer_id in range(1, total_customers + 1):
        customer_thread = threading.Thread(target=barber_shop.customer, args=(customer_id,))
        customer_thread.start()
        time.sleep(random.randint(1, 2))  # Customers arrive every 1-2 seconds
if __name__ == "__main__":
    main()

What’s Going On in the Code?

Let’s break down the code for the Sleeping Barber Problem step by step so you can fully understand how it works and how each part fits together. This will help you grasp how concurrency and synchronization are managed in the barber shop simulation.

1. BarberShop Class Setup:

The first thing we do is create the BarberShop class. This class handles everything that happens inside the shop — how many customers are waiting, whether the shop is open, and how the barber and customers interact.

— num_chairs represents the number of waiting room chairs available for customers.
— total_customers tracks the total number of customers the shop will serve.
— waiting_customers keeps count of how many customers are currently sitting in the waiting room.
— shop_open is a flag that controls whether the barber is still accepting customers.
— barber_ready and customer_ready are condition variables that help synchronize the barber and customer threads, ensuring they communicate properly.

2. Opening the Barber Shop:

The open_shop method is where the barber starts working. This method spawns a new thread for the barber, allowing them to run concurrently with customers arriving. When you call this method, the barber is essentially “clocking in” for work.

3. Barber’s Work (barber method):

This method runs continuously in a loop, representing the barber’s working day.

— First, the barber checks whether there are any customers waiting by acquiring the customer_ready lock. If there are no customers (i.e., waiting_customers == 0), the barber goes to sleep by calling customer_ready.wait(). This releases the lock and waits for a notification that a customer has arrived.
— When a customer shows up, the barber wakes up, reduces the count of waiting customers (self.waiting_customers -= 1), and starts cutting hair (simulated by time.sleep()).
— After finishing the haircut, the barber notifies the next customer (if any) that they can come up for their turn by calling barber_ready.notify().
— The barber repeats this loop until all customers have been served.

4. Customer Arriving (customer method):

This method simulates each customer arriving at the shop.

— When a customer arrives, they check if there is a free chair in the waiting room by acquiring the customer_ready lock. If there’s room, they sit down, increment the count of waiting customers (self.waiting_customers += 1), and notify the barber that they are ready for a haircut.
— If the waiting room is full, the customer leaves, and no further action is taken (return exits the function).
— After notifying the barber, the customer waits until the barber is ready to give them a haircut (barber_ready.wait()), ensuring that only one customer sits in the barber chair at a time.

5. Main Function (main):

This is where the simulation kicks off. The barber shop is opened by calling barber_shop.open_shop(), which starts the barber’s thread. Then, customer threads are created in a loop, simulating customers arriving one by one at random intervals.

— time.sleep(random.randint(1, 2)) adds a random delay between customer arrivals to make the simulation more realistic. Customers don’t arrive all at once but spread out over time.

6. Condition Variables and Locking:

Two key condition variables, barber_ready and customer_ready, help synchronize communication between the barber and customers:

— customer_ready: Used by customers to notify the barber that they are waiting. The barber sleeps when no customers are ready and wakes up when notified by a customer.
— barber_ready: Used by the barber to notify the customer that their haircut is finished and the next customer can come up. Customers wait until the barber is ready for them.

7. Customer and Barber Synchronization

The condition variables ensure that customers don’t try to sit in the barber’s chair while it’s occupied and that the barber doesn’t try to cut hair when there are no customers. It’s a give-and-take process: the barber works when customers are waiting, and customers wait their turn when the barber is busy.

Real-World Applications of the Sleeping Barber Problem

At first glance, the Sleeping Barber Problem may seem like an abstract puzzle or a fun thought experiment. But in reality, it has practical applications that are very relevant to the world of computing and technology. Let’s break down a few examples where this problem comes into play in real life:

Web Servers: Imagine a busy website where thousands of users are trying to access it at the same time. Web servers need to handle requests from all these users with limited resources, such as available threads or database connections. Just like the barber can only serve a few customers at a time, the server has to manage incoming requests carefully to avoid overload and ensure that everyone gets served efficiently.

Operating Systems: In an operating system, many processes (or programs) are running at the same time, all needing access to limited resources like CPU cores or memory. The system has to decide which processes get to use these resources, similar to how the barber decides which customer gets a haircut next. The operating system needs to keep everything running smoothly while making sure no process waits too long.

Databases: Databases are often accessed by multiple users or applications at once, especially in multi-user environments. The system has to ensure that access to data is synchronized, so everyone gets consistent information without causing conflicts or errors (like race conditions). Think of this like the barber making sure no two customers are trying to sit in the same chair at once!

In short, the Sleeping Barber Problem highlights important strategies for managing limited resources in a way that keeps things running smoothly, whether it’s on a server, in an operating system, or within a database.

Wrapping It Up

And there you have it! The Sleeping Barber Problem is a great way to get your feet wet with concepts like concurrency, synchronization, and resource management. We saw how the barber and customers represent tasks competing for limited resources, and we learned how to keep things running smoothly without chaos. These concepts are super important when you’re building apps or systems that need to handle a bunch of things at once — like servers or databases.

But we’re not done yet! Up next, we’re diving into the Dining Philosophers Problem, which is another fun challenge that builds on what we’ve learned here. In that one, we’ll tackle how multiple philosophers (or processes) can share limited forks (resources) without getting stuck or starving. It’s going to be even more interesting, so stay tuned!

If you’d rather not copy and paste code from this post, I’ve got you covered! You can check out the full code for the Sleeping Barber Problem on GitHub. Feel free to clone it, experiment with it, and make it your own.