spinlock,mutex,semaphore,critical section的作用和區別

Mutex是一把鑰匙,一個人拿了就可進入一個房間,出來的時候把鑰匙交給隊列的第一個。一般的用法是用於串行化對critical section代碼的訪問,保證這段代碼不會被並行的運行。
(A mutex is really a semaphore with value 1.)

Semaphore是一件可以容納N人的房間,如果人不滿就可以進去,如果人滿了,就要等待有人出來。對於N=1的情況,稱為binary semaphore。一般的用法是,用於限制對於某一資源的同時訪問。

Binary semaphore與Mutex的差異:

在有的系統中Binary semaphore與Mutex是沒有差異的。在有的系統上,主要的差異是mutex一定要由獲得鎖的進程來釋放。而semaphore可以由其它進程釋放(這時的semaphore實際就是個原子的變量,大家可以加或減),因此semaphore可以用於進程間同步。 Semaphore的同步功能是所有系統都支持的,而Mutex能否由其他進程釋放則未定,因此建議mutex只用於保護critical section。而semaphore則用於保護某變量,或者同步。

另一個概念是spin lock,這是一個內核態概念。 spin lock與semaphore的主要區別是spin lock是busy waiting,而semaphore是sleep。對於可以sleep的進程來說,busy waiting當然沒有意義。對於單CPU的系統,busy waiting當然更沒意義(沒有CPU可以釋放鎖)。因此,只有多CPU的內核態非進程空間,才會用到spin lock。 Linux kernel的spin lock在非SMP的情況下,只是關irq,沒有別的操作,用於確保該段程序的運行不會被打斷。其實也就是類似mutex的作用,串行化對critical section的訪問。但是mutex不能保護中斷的打斷,也不能在中斷處理程序中被調用。而spin lock也一般沒有必要用於可以sleep的進程空間。

Mutex vs. Semaphore, what is the difference?

The Toilet Example (c) Copyright 2005, Niclas Winquist ;)


Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue.

Officially: "Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section."
Ref: Symbian Developer Library

(A mutex is really a semaphore with value 1.)


Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

Officially: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)."
Ref: Symbian Developer Library

BB 發表在 痞客邦 PIXNET 留言(0) 人氣()