互斥指互斥的鎖,是一種訊號量,常用來防止兩個進程或線程在同一時刻訪問相同的共用資源
1.資料類型:
在Linux下, 線程的互斥量資料類型是pthread_mutex_t,我們定義一個互斥資料可以這樣:
pthread_mutex_t mutex;
2.函數說明:
標頭檔: pthread.h
(1).互斥鎖初始化:
函數原型: int pthread_mutex_init (pthread_mutex_t* mutex,
const pthread_mutexattr_t* mutexattr);
函數傳入值: mutex:互斥鎖。
mutexattr:PTHREAD_MUTEX_INITIALIZER:建立快速互斥鎖。
PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP:建立遞迴互斥鎖。
PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP:建立檢錯互斥鎖。
函數傳回值: 成功:0
出錯:-1
(2).互斥操作函數
int pthread_mutex_lock(pthread_mutex_t* mutex);//上鎖
int pthread_mutex_trylock (pthread_mutex_t* mutex);//只有在互斥被鎖住的情況下才阻塞
int pthread_mutex_unlock (pthread_mutex_t* mutex);//解鎖
int pthread_mutex_destroy (pthread_mutex_t* mutex);//清除互斥鎖
函數傳入值: mutex:互斥鎖。
函數傳回值: 成功:0
出錯:-1
3.使用形式:
struct mutex mutex;
mutex_init(&mutex); /*定義*/
...
mutex_lock(&mutex); /*擷取互斥鎖*/
... /*臨界資源*/
mutex_unlock(&mutex); /*釋放互斥鎖*/
最後進行一個練習:我們建立兩個線程,分別訪問全域變數gnum,並且修改它,列印出來
[cpp] view plaincopy
- /*mutex.c*/
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
- #include <errno.h>
- /*全域變數*/
- int gnum = 0;
- /*互斥量 */
- pthread_mutex_t mutex;
- /*聲明線程運行服務程式*/
- static void pthread_func_1 (void);
- static void pthread_func_2 (void);
-
- int main (void)
- {
- /*線程的標識符*/
- pthread_t pt_1 = 0;
- pthread_t pt_2 = 0;
- int ret = 0;
- /*互斥初始化*/
- pthread_mutex_init (&mutex, NULL);
- /*分別建立線程1、2*/
- ret = pthread_create (&pt_1, //線程標識符指標
- NULL, //預設屬性
- (void *)pthread_func_1,//運行函數
- NULL); //無參數
- if (ret != 0)
- {
- perror ("pthread_1_create");
- }
-
- ret = pthread_create (&pt_2, //線程標識符指標
- NULL, //預設屬性
- (void *)pthread_func_2, //運行函數
- NULL); //無參數
- if (ret != 0)
- {
- perror ("pthread_2_create");
- }
- /*等待線程1、2的結束*/
- pthread_join (pt_1, NULL);
- pthread_join (pt_2, NULL);
-
- printf ("main programme exit!/n");
- return 0;
- }
- /*線程1的服務程式*/
- static void pthread_func_1 (void)
- {
- int i = 0;
-
- for (;;)
- {
- printf ("This is pthread1!/n");
- pthread_mutex_lock(&mutex); /*擷取互斥鎖*/
- /*注意,這裡以防線程的搶佔,以造成一個線程在另一個線程sleep時多次訪問互斥資源,所以sleep要在得到互斥鎖後調用*/
- sleep (1);
- /*臨界資源*/
- gnum++;
- printf ("Thread1 add one to num:%d/n",gnum);
- pthread_mutex_unlock(&mutex); /*釋放互斥鎖*/
-
-
- }
- }
- /*線程2的服務程式*/
- static void pthread_func_2 (void)
- {
- int i = 0;
-
- for (;;)
- {
- printf ("This is pthread2!/n");
- pthread_mutex_lock(&mutex); /*擷取互斥鎖*/
- /*注意,這裡以防線程的搶佔,以造成一個線程在另一個線程sleep時多次訪問互斥資源,所以sleep要在得到互斥鎖後調用*/
- sleep (1);
- /*臨界資源*/
- gnum++;
- printf ("Thread2 add one to num:%d/n",gnum);
- pthread_mutex_unlock(&mutex); /*釋放互斥鎖*/
-
- }
-
- pthread_exit (0);
- }
然後編譯,運行,看到是線程1,2分別和平地訪問共用資源