在多線程編程中枷恕, 為保證共享數(shù)據(jù)的完整性醋虏,引入互斥鎖的概念寻咒,每個(gè)對(duì)象可以有一個(gè)mutex這樣的標(biāo)記,來標(biāo)示這個(gè)對(duì)象在某一時(shí)刻只能被一個(gè)線程訪問颈嚼。
多線程程序一般使用互斥量來對(duì)臨界區(qū)進(jìn)行保護(hù)毛秘,臨界區(qū)只允許加上互斥鎖的那個(gè)線程來訪問,其它的線程要等鎖釋放后重新加鎖阻课。
例如下面簡(jiǎn)單的程序叫挟,不加鎖的情況下,任意線程都可以訪問限煞,導(dǎo)致a的值不可控制抹恳。
int get_a()
{
a++;
return a;
}
加鎖之后,則同一時(shí)刻只會(huì)有一個(gè)線程訪問署驻。
int get_a()
{
lock(mutex);
a++;
unlock(mutex);
return a;
}
這個(gè)接口則是線程安全的奋献。
另外互斥鎖還分為幾種類型
- 普通鎖
- 嵌套鎖
- 糾錯(cuò)鎖
- 自適應(yīng)鎖
下面用兩個(gè)例子來說明一下普通鎖和糾錯(cuò)鎖。
編程時(shí)一般約定某個(gè)線程加的鎖只能由自身來釋放旺上,但是普通鎖可以解別的線程加的鎖瓶蚂。
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
//靜態(tài)方式創(chuàng)建
pthread_mutex_t tMutex = PTHREAD_MUTEX_INITIALIZER;
int count;
void *TdFunc(void *ptr)
{
pthread_t tid;
int i = *((int *)(ptr));
int ret = 0;
//獲得線程自身的id
tid = pthread_self();
//將該線程的狀態(tài)設(shè)為detached,則該線程運(yùn)行結(jié)束后會(huì)釋放所有資源宣吱。
pthread_detach(tid);
if (0 == i % 2) {
printf("%u try to lock mutex\n", tid);
ret = pthread_mutex_lock(&tMutex);
if (0 == ret) {
printf("%u lock mutex succ\n", tid);
} else {
printf("%u lock mutex failed\n", tid);
}
} else {
printf("%u try to unlock mutex\n", tid);
ret = pthread_mutex_unlock(&tMutex);
if (0 == ret) {
printf("%u try to unlock mutex succ\n", tid);
} else {
printf("%u unlock mutex failed\n", tid);
}
}
count++;
}
int main(int argc, char *argv[])
{
int i = 0;
int ret = 0;
//pthread不是linux系統(tǒng)默認(rèn)的庫(kù)窃这,連接時(shí)需要使用靜態(tài)庫(kù)libthread.a
for (i = 0; i < atoi(argv[1]); ++i) {
pthread_t tid;
printf("%u\n", tid);
ret = pthread_create(&tid, NULL, TdFunc, &i);
if (0 != ret) {
strerror(ret);
return 0;
}
sleep(1);
}
while(count < 5);
return 0;
}