Linux下,爲了線程安全,爲我們提供了很多種鎖。
讀寫鎖: 我們在編寫多線程的時候,我們可能需要經常去讀取某個共享數據變量,但是相對要改寫這個變量的機會相對較少。在讀的過程中,往往伴隨着查找的操作,中間耗時很長,給這種代碼加鎖,會極大的降低我們程序的效率。所以提出了讀寫鎖。
注意:寫獨佔,讀共享,寫鎖優先級高
例子:4個讀線程,4個寫線程
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
pthread_rwlock_t rwlock; //定義讀寫鎖
int counter;
void *rrout(void *arg) //讀線程函數
{
int t;
int i = *(int *)arg;
free(arg);
while(1)
{
pthread_rwlock_rdlock(&rwlock);
printf("read:%d : %#X : counter= %d\n",i,pthread_self(),counter);
pthread_rwlock_unlock(&rwlock);
usleep(1111);
}
}
void *wrout(void *arg) //寫線程函數
{
int t;
int i = *(int *)arg;
free(arg);
while(1)
{
t = counter;
usleep(1000);
pthread_rwlock_rdlock(&rwlock);
printf("write:%d : %#X : counter= %d, ++counter = %d\n",i,pthread_self(),counter,++counter);
pthread_rwlock_unlock(&rwlock);
usleep(11111);
}
}
int main()
{
int i = 0 ;
pthread_t tid[8];
pthread_rwlock_init(&rwlock,NULL); //讀寫鎖初始化
for(i = 0; i < 4; i ++)
{
int *p = (int *)malloc(sizeof(int));
*p = i;
pthread_create(&tid[i],NULL,rrout,(void *)p);
}
for(i = 0; i < 4; i ++)
{
int *p = (int *)malloc(sizeof(int));
*p = i;
pthread_create(&tid[i + 4],NULL,wrout,(void *)p);
}
for(i = 0; i < 8; i++)
{
pthread_join(tid[i],NULL);
}
pthread_rwlock_destroy(&rwlock); //銷燬讀寫鎖
運行結果: