目錄
一 開發環境
系統:Ubuntu16.04
線程庫:pthread
語言:c/c++
Linux下的線程保護,最常用的是互斥鎖、條件變量、信號量和讀寫鎖。
先來試一下互斥鎖吧
二 互斥鎖
多線程之間可能需要互斥的訪問一些全局變量,這就需要互斥的來訪問,這些需要共享訪問的字段被稱作是臨界資源,訪問臨界資源的程序段稱作是臨界區。
實現線程間的互斥與同步機制的是鎖機制,下面是常用的鎖機制的函數和類。
pthread_mutex_t mutex
鎖對象pthread_mutex_init(&mutex,NULL)
在主線程中初始化鎖爲解鎖狀態pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER
編譯時初始化鎖爲解鎖狀態pthread_mutex_lock(&mutex)(阻塞加鎖)
訪問臨界區加鎖操作- pthread_mutex_trylock( &mutex)(非阻塞加鎖); pthread_mutex_lock() 類似,不同的是在鎖已經被佔據時返回 EBUSY 而不是掛起等待。
pthread_mutex_unlock(&mutex)
: 訪問臨界區解鎖操作
示例代碼:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
int num = 0;
void thread_num(void);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main()
{
int ret;
pthread_t thread1,thread2,thread3;
ret = pthread_create(&thread1,NULL,(void *)&thread_num,NULL);
ret = pthread_create(&thread2,NULL,(void *)&thread_num,NULL);
ret = pthread_create(&thread3,NULL,(void *)&thread_num,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
pthread_join(thread3,NULL);
return 0;
}
void thread_num(void)
{
for(int i=0;i<3;++i)
{
if(pthread_mutex_lock(&mutex) != 0)
{
perror("pthread_mutex_lock");
}
num++;
printf("%u:num=%d\n",pthread_self(),num);
if(pthread_mutex_unlock(&mutex) != 0)
{
perror("pthread_mutex_unlock");
}
sleep(1);
}
}
運行結果: