OS

[OS] Lock, Semaphore, Monitor

mjk- 2023. 12. 13. 07:26

Concurrency를 지키기 위한 3가지의 툴에 대한 노트입니다.

* All the code below is a harmony code

 

Before we start, it is important to mention Atomic Section IS NOT Critical Section

Atomic Section (Mutex)  Critical Section
- one thread running among different processes
- Single Thread: no other threads can run while running t1
- good for interlock instruction
- one thread running within one process
- multiple threads execution: makes sure the only code is running on t1
- locks available
- good for concurrent data structures

 

Lock


A lock is binary (taken / not taken) ---> same thread acq & release

- take with acquire() & put back with release()

- is busy waiting/uses conditional waiting: wait for condition to be met in while loop

- ensures one thread execution per one process  = critical section.

 

Mutex lock implemented:

 

  • note that we release & acquire in a while loop. 
    • release not to block other threads (no take & wait = no deadlock)
    • acquire for the incrementation (next line) 

 

Semaphore


Binary Semaphore = allow multiple threads to enter cs ---> can be released by a different thread

  • if n waiting conditions, need n+1 binary semaphores to protect CS
    •  ex) reading, writing, mutex
  • Operations in harmony
  1. INIT       lk=BinSema(False or True) : can initialized to be F/T (unlike lock!)
  2. Acq (P) acquire(?lk) : waits until !lk = False, set lk = true
  3. Rel (V)  release(?lk) : 

Split Binary Semaphore: multiple binary semaphores --> it's like opening doors (BinSema)

Lock Binary Semaphore
- initially unlocked (False)
- acq & rel by the same thread
- 1 thread only in CS
- used to implement CS

- init False / True
- can be acquired & released by different threads
- implement CS & conditioned waiting
Busy waiting split binary semaphore 
- check condition in loop - acq & rel lock until condition is T
- pro: easy to understand
- con: OK for multicore (multi-processing) & BAD for virtual threads (multi-threading)
- use collection of binary semaphores to keep track of state, wiaintg threads
- pro: Good for both multicore & virtual threads
- con: hard to understand

 

Mesa Monitor


 

 

Reference: Prof. Lorenzo & Stackoverflow

 

 

'OS' 카테고리의 다른 글

Basic Operating Systems  (0) 2023.12.12