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

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
Threatpost
P
Privacy International News Feed
T
Tenable Blog
Know Your Adversary
Know Your Adversary
C
Cisco Blogs
P
Proofpoint News Feed
Spread Privacy
Spread Privacy
G
GRAHAM CLULEY
爱范儿
爱范儿
U
Unit 42
K
Kaspersky official blog
C
Cybersecurity and Infrastructure Security Agency CISA
Jina AI
Jina AI
O
OpenAI News
L
LangChain Blog
PCI Perspectives
PCI Perspectives
P
Privacy & Cybersecurity Law Blog
Latest news
Latest news
Cisco Talos Blog
Cisco Talos Blog
F
Full Disclosure
L
Lohrmann on Cybersecurity
V
V2EX
L
LINUX DO - 热门话题
S
Security Affairs
量子位
Martin Fowler
Martin Fowler
云风的 BLOG
云风的 BLOG
Schneier on Security
Schneier on Security
月光博客
月光博客
MyScale Blog
MyScale Blog
C
CERT Recently Published Vulnerability Notes
AWS News Blog
AWS News Blog
博客园 - 叶小钗
Forbes - Security
Forbes - Security
W
WeLiveSecurity
T
Troy Hunt's Blog
J
Java Code Geeks
Hacker News - Newest:
Hacker News - Newest: "LLM"
Google DeepMind News
Google DeepMind News
Attack and Defense Labs
Attack and Defense Labs
Apple Machine Learning Research
Apple Machine Learning Research
雷峰网
雷峰网
Google Online Security Blog
Google Online Security Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
TaoSecurity Blog
TaoSecurity Blog
H
Help Net Security
The Cloudflare Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

博客园 - 北叶青藤

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 1242. Web Crawler Multithreaded Python Multi-threading 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
1114. Print in Order
北叶青藤 · 2026-07-16 · via 博客园 - 北叶青藤

Suppose we have a class:

public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}

The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().

Note:

We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.

Example 1:

Input: nums = [1,2,3]
Output: "firstsecondthird"
Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output.

Example 2:

Input: nums = [1,3,2]
Output: "firstsecondthird"
Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the correct output. 

Constraints:

  • nums is a permutation of [1, 2, 3].

Solution 1: Lock (Most Common)

The idea is simple:

  • first() runs immediately.
  • second() waits until first() finishes.
  • third() waits until second() finishes.
from threading import Lock

class Foo:
    def __init__(self):
        self.lock2 = Lock()
        self.lock3 = Lock()

        self.lock2.acquire()
        self.lock3.acquire()

    def first(self, printFirst: 'Callable[[], None]') -> None:
        printFirst()
        self.lock2.release()

    def second(self, printSecond: 'Callable[[], None]') -> None:
        with self.lock2:
            printSecond()
            self.lock3.release()

    def third(self, printThird: 'Callable[[], None]') -> None:
        with self.lock3:
            printThird()

Solution 2: Semaphore (Very Common)

This is probably the cleanest solution.

Why Semaphore(0)?

Initial permits:

Calling

blocks until someone calls

So


Solution 3: Condition Variable

Here:

  • stage == 1 → first should run
  • stage == 2 → second should run
  • stage == 3 → third should run

Always use a while loop instead of if around wait() to handle spurious wakeups.


Solution 4: Event (Simplest)

Python's Event is designed exactly for "wait until something happens."

An Event behaves like a boolean flag:

  • Initially False.
  • wait() blocks until the flag becomes True.
  • set() changes the flag to True and wakes all waiting threads.

Interview rule of thumb

When designing concurrent systems:

  • Need mutual exclusion?
    Lock
  • Need N threads/resources at the same time?
    Semaphore
  • Need to wait for a condition/state change?
    Condition
  • Need one thread to broadcast "I am ready/done/stopped"?
    Event

A good mental model: