由於執行緒之間的絕大多數資源都是共享的,當多個執行緒同時訪問乙個資源時,可能會出現資料不完整、不一致的情況,此時就需要多個執行緒協調訪問資源(競爭訪問,需要用於互斥技術),最終達到資料一致、完整(同步)。
也叫互斥鎖,當互斥量處於鎖定狀態時,其他執行緒加鎖會處於阻塞狀態,只有鎖被開啟時,被阻塞的執行緒才能繼續執行
int
pthread_mutex_init
(pthread_mutex_t *mutex,
const pthread_mutexattr_t *mutexattr)
;功能:初始化互斥量,也可以使用pthread_mutex_initializer初始化。
intpthread_mutex_lock
(pthread_mutex_t *mutex)
;功能:給互斥量加鎖,如果處理鎖定狀態,則當前執行緒阻塞。
intpthread_mutex_trylock
(pthread_mutex_t *mutex)
;功能:嘗試給互斥量加鎖,能鎖則鎖,不能鎖則返回錯誤。
intpthread_mutex_unlock
(pthread_mutex_t *mutex)
;功能:給互斥量解鎖
intpthread_mutex_destroy
(pthread_mutex_t *mutex)
;功能:銷毀互斥量
r r ok
w w no
r w no
w r no
int
pthread_rwlock_init
(pthread_rwlock_t *restrict rwlock,
const pthread_rwlockattr_t *restrict attr)
;int
pthread_rwlock_destroy
(pthread_rwlock_t *rwlock)
;int
pthread_rwlock_rdlock
(pthread_rwlock_t *rwlock)
;int
pthread_rwlock_tryrdlock
(pthread_rwlock_t *rwlock)
;int
pthread_rwlock_trywrlock
(pthread_rwlock_t *rwlock)
;int
pthread_rwlock_wrlock
(pthread_rwlock_t *rwlock)
;int
pthread_rwlock_unlock
(pthread_rwlock_t *rwlock)
;
舉例:使用讀寫鎖解決執行緒同步問題
#include
#include
#include
#define thread_cnt (10)
int num;
pthread_rwlock_t rwlock;
void
*run
(void
* arg)
}int
main()
for(
int i=
0; i)printf
("num:%d\n"
,num)
;}
同步 互斥鎖與條件變數 讀寫鎖 訊號量
1.靜態分配互斥量 pthread mutex t mutex pthread mutex initializer 2.動態分配互斥量 pthread mutex init mutex pthread mutex destory mutex 操作 1.pthread mutex lock 加鎖 2....
互斥量與讀寫鎖操作函式
互斥變數是用 pthread mutex t 資料型別表示的。下面幾個函式可操作互斥量。include int pthread mutex init pthread mutex t restrict mutex,const pthread mutexattr t restrict attr int ...
同步 互斥鎖 讀寫鎖 區別
相交程序之間的關係主要有兩種,同步與互斥。所謂互斥,是指散步在不同程序之間的若干程式片斷,當某個程序執行其中乙個程式片段時,其它程序就不能執行它 們之中的任一程式片段,只能等到該程序執行完這個程式片段後才可以執行。所謂同步,是指散步在不同程序之間的若干程式片斷,它們的執行必須嚴格按照規定的 某種先後...