Mutex vs. Semaphore vs Spin lock

1.Mutex
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."
A mutex is really a semaphore with value 1.
(Ref: Symbian Developer Library)

2. Semaphore:
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)

3. My understanding:
MUTEX作爲互斥量,用於關鍵區域的互斥操作。它是有歸屬的,就是一個MUTEX必須是由得到它的進程或者任務進行釋放。
而二值信號量則不用。任何一個 任務都可以post一個信號量,而釋放一個MUTEX必須由擁有它的進程來完成。
我的理解就是在使用的時候,MUTEX在一個任務裏面應該成對的使用,而二值信號量則不必如此。
因此在中斷處理函數裏面應該使用二值信號量而不是MUTEX.

From Internet:
1、臨界區只能用於對象在同一進程裏線程間的互斥訪問;互斥體可以用於對象進程間或線程間的互斥訪問。
2、臨界區是非內核對象,只在用戶態進行鎖操作,速度快;互斥體是內核對象,在覈心態進行鎖操作,速度慢。
3、臨界區和互斥體在Windows平臺都下可用;Linux下只有互斥體可用。

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

4.Spin Lock
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的進程空間。

5. 自旋鎖和信號量對比
(Internet)在很多地方自旋鎖和信號量可以選擇任何一個使用,但也有一些地方只能選擇某一種。下面對比一些兩者的用法。

        表1-1自旋鎖和信號量對比
 應用場合                                                                 信號量or自旋鎖
 低開銷加鎖(臨界區執行時間較快)                 優先選擇自旋鎖
 低開銷加鎖(臨界區執行時間較長)                 優先選擇信號量
 臨界區可能包含引起睡眠的代碼                         不能選自旋鎖,可以選擇信號量
 臨界區位於非進程上下文時,此時不能睡眠     優先選擇自旋鎖,即使選擇信號量也
                                                                                  只能用down_trylock非阻塞的方式

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章