一、執行緒間通訊-互斥
1.臨界資源:一次只允許乙個任務
2.臨界區:訪問臨界區的**
3.互斥機制----1>mutex互斥鎖
2>鎖的使用過程:任務訪問臨界資源前申請鎖,訪問完釋放鎖
二、函式介紹
1.互斥鎖的初始化
方法1:動態方式建立互斥鎖
#include
intpthread_mutex_init
(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr)
;返回值:成功返回0,失敗返回錯誤碼
引數:1
-mutex 要初始化的互斥鎖的物件
2-attr 互斥鎖的屬性,null代表屬性預設
方法2:靜態方式建立互斥鎖
pthread_mutex_t lock = pthread_mutex_initializer;
注:pthread_mutex_t是乙個結構,而pthread_mutex_initializer則是乙個結構常量
2.上鎖(申請鎖)
#include
intpthread_mutex_lock
(pthread_mutex_t *mutex)
;
3.釋放鎖(訪問完臨界資源要及時釋放鎖,避免死鎖的產生)
#include
intpthread_mutex_unlock
(pthread_mutex_t *mutex)
;
4.銷毀鎖
#include
intpthread_mutex_destroy
(&lock)
;
三、**演練
#include
#include
#include
#include
void
*thread_function1
(void
*arg)
;void
*thread_function2
(void
*arg)
;//靜態初始化
pthread_mutex_t lock = pthread_mutex_initializer;
intmain
(int argc,
const
char
*ar**)
*/ ret =
pthread_create
(&tid1,
null
, thread_function1,
null);
if(0!= ret)
ret =
pthread_create
(&tid2,
null
, thread_function2,
null);
if(0!= ret)
ret =
pthread_join
(tid1,
null);
if(0!= ret)
ret =
pthread_join
(tid2,
null);
if(0!= ret)
ret =
pthread_mutex_destroy
(&lock);if
(0!= ret)
return0;
}void
*thread_function1
(void
*arg)
for(i =
1; i <=
3; i++
)//unlock
ret =
pthread_mutex_unlock
(&lock);if
(0!= ret)
return
null;}
void
*thread_function2
(void
*arg)
for(i =
1; i <=
3; i++
)//unlock
ret =
pthread_mutex_unlock
(&lock);if
(0!= ret)
return
null
;}
執行結果:
通過加鎖控制了執行緒的執行順序
執行緒 互斥鎖
include include include include include 1.靜態初始化,當動態初始化時,遮蔽靜態初始化 pthread mutex t mutex pthread mutex initializer 2.動態初始化 pthread mutex t mutex int lock...
執行緒互斥鎖
執行緒互斥鎖 降低效率,保證資料安全 執行緒 資料共享 修改共享資料,資料不安全 from threading import thread,lock import time n 100 deftask global n temp n time.sleep 0.1 n temp 1 if name m...
執行緒的互斥鎖
1.執行緒的互斥鎖 1.1.初始化 在linux下,執行緒的互斥量資料型別是pthread mutex t.在使用前,要對它進行初始化 對於靜態分配的互斥量,可以把它設定為pthread mutex initializer,或者呼叫pthread mutex init.對於動態分配的互斥量,在申請記...