SystemsOperating Systems

Concurrency & Synchronization

Summary of Race Condition, Mutex, Semaphore, and Deadlock

Concurrency & Synchronization (Quick Summary)

1. Race Condition

A situation where multiple Threads or Processes attempt to read and write Shared Data simultaneously, causing the final result to be corrupted and unpredictable.

  • Critical Section: A segment of code that accesses Shared Resources, which must be protected to prevent overlapping execution.

2. Synchronization Mechanisms

Mechanisms that the OS or Language Runtime uses to control access to the Critical Section.

  • Mutex (Mutual Exclusion): A 1:1 Lock mechanism that allows only a single Thread to enter the Critical Section (only the owner of the Lock can release the Lock).
  • Semaphore: A signaling mechanism that limits the number of Threads that can access a Resource concurrently.
    • Binary Semaphore: Has a value of 0 or 1 (similar to Mutex, but anyone can release the Lock).
    • Counting Semaphore: Allows N entities to access concurrently (e.g., Database Connection Pool).

3. Deadlock

A state where 2 or more Processes/Threads are permanently locked because they are all waiting for Resources held by each other.

  • 4 Conditions for Deadlock (Coffman Conditions):
    1. Mutual Exclusion: Resources are held exclusively.
    2. Hold and Wait: Holding Resource A while waiting to request Resource B.
    3. No Preemption: The OS cannot forcefully take a Resource back from a Process.
    4. Circular Wait: Waiting in a circular loop.
  • Solution: One of the conditions must be broken (e.g., forcing resources to be requested in a specific order to prevent Circular Wait).

AI Knowledge Assistant

สวัสดีครับ! ผมคือ AI Assistant ประจำเว็บไซต์

คุณสามารถสอบถามข้อมูลด้าน Computer Science, Business, หรือ Finance ได้เลยครับ