內核同步機制之Mutex Exclusion

S3C2440在內核版本2.6.34下開發ADC驅動時,會發現驅動程序裏用了互斥通訊來實現同步:數據結構

<!-- lang: cpp -->
DECLARE_MUTEX(ADC_LOCK);
static int OwnADC = 0;

在wikipedia中式這麼定義Mutex Exclusion的:函數

In computer science, mutual exclusion refers to the requirement of ensuring that no two processes or threads (henceforth referred to only as processes) are in their critical section at the same time. Here, a critical section refers to a period of time when the process accesses a shared resource, such as shared memory.ui

專業的表達也能夠是這樣:線程

A data structure for mutual exclusion, also known as a binary semaphore. A mutex is basically just a multitasking-aware binary flag that can be used to synchronize the activities of multiple tasks. As such, it can be used to protect critical sections of the code from interruption and shared resources from simultaneous use.code

互斥體是表現互斥現象的數據結構,也被看成二元信號燈。一個互斥基本上是一個多任務敏感的二元信號,它能用做同步多任務的行爲,它經常使用做保護從中斷來的臨界段代碼而且在共享同步使用的資源。ip

##使用## Linux內核的同步機制裏面: 輔助宏:ci

<!-- lang: cpp -->
DECLARE_MUTEX(name); /*聲明一個互斥鎖,把名爲name的信號量變量初始化爲1 */
DECLARE_MUTEX_LOCKED(name); /* 聲明一個互斥鎖,把名爲name的信號量變量初始化爲0 */

在Linux世界中, P函數被稱爲down, 指的是該函數減少了信號量的值, 它也許會將調用者置於休眠狀態, 而後等待信號量變得可用, 以後再授予調用者對被保護資源的訪問權限.資源

<!-- lang: cpp -->
void down(struct semaphore *sem);

當一個線程成功調用down函數後, 就稱爲該線程擁有了該信號量, 能夠訪問被該信號量保護的臨界區. 當互斥操做完成後, 必須釋放該信號量. Linux的V函數是up:開發

<!-- lang: cpp -->
void up(struct semaphore *sem)

調用up以後, 調用者再也不擁有該信號量rem

##Reference## [1].Linux Device Drivers.Thirth Edition.P112-P114

相關文章
相關標籤/搜索