linux多线程之读写锁

来源:互联网 发布:mac office无法更新 编辑:程序博客网 时间:2024/05/17 01:58
Pthread是 POSIX threads 的简称,是POSIX的线程标准
        pthread读写锁把对共享资源的访问者分为读者写者,读者只对共享资源进行读访问,写者只对共享资源进行写操作。在互斥机制,读者和写者都需要独立独占互斥量以独占共享资源,在读写锁机制下,允许同时有多个读者读访问共享资源,只有写者才需要独占资源。相比互斥机制,读写机制由于允许多个读者同时读访问共享资源,进一步提高了多线程的并发度。
         
       1.读写锁机制

       写者:写者使用写锁,如果当前没有读者,也没有其他写者,写者立即获得写锁;否则写者将等待,直到没有读者和写者。
       读者:读者使用读锁,如果当前没有写者,读者立即获得读锁;否则读者等待,直到没有写者。
           
          2.读写锁特性

        同一时刻只有一个线程可以获得写锁,同一时刻可以有多个线程获得读锁。
        读写锁出于写锁状态时,所有试图对读写锁加锁的线程,不管是读者试图加读锁,还是写者试图加写锁,都会被阻塞。
       读写锁处于读锁状态时,有写者试图加写锁时,之后的其他线程的读锁请求会被阻塞,以避免写者长时间的不写锁。
        
        3.读写锁基本函数
         # include<pthread.h>
读写锁初始化:
        int pthread_rwlock_init(pthread_rwlock_t * rwlock, 
                                                 const pthread_rwlockattr_t *  attr);
        该函数第一个参数为读写锁指针,第二个参数为读写锁属性指针。函数按读写锁属性对读写锁进行初始化。
加读锁:
        int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
        该函数参数为读写锁指针。函数用于对读写锁加读锁。
加写锁:
        int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
        该函数参数为读写锁指针。函数用于对读写锁加写锁。
释放读写锁:
        int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
        该函数参数为读写锁指针。函数用于释放读写锁,包括读锁与写锁。
销毁读写锁:
        int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
        该函数参数为读写锁指针。函数用于销毁读写锁。

        4.牛刀小试
        示例使用读写锁,对共享资源data进行读写同步,线程readerM,readerN为读者线程,线程writerA,writerB为写者线程。       
  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
#include <stdio.h>
#include <Windows.h>
#include <pthread.h>
#include <semaphore.h>
#pragma comment(lib, "pthreadVC2.lib") //必须加上这句
pthread_t t1; //pthread_t变量t1,用于获取线程1的ID
pthread_t t2; //pthread_t变量t2,用于获取线程2的ID
pthread_rwlock_t rwlock; //声明读写锁
int data=1; //共享资源
void* readerM(void* arg)
{
while(1)
{
pthread_rwlock_rdlock(&rwlock); //读者加读锁
printf("M 读者读出: %d \n",data); //读取共享资源
pthread_rwlock_unlock(&rwlock); //读者释放读锁
Sleep(1200);
}
return NULL;
}
void* readerN(void* arg)
{
while(1)
{
pthread_rwlock_rdlock(&rwlock);
printf(" N读者读出: %d \n",data);
pthread_rwlock_unlock(&rwlock);
Sleep(700);
}
return NULL;
}
void* writerA(void* arg)
{
while(1)
{
pthread_rwlock_wrlock(&rwlock); //写者加写锁
data++; //对共享资源写数据
printf("A写者写入: %d\n",data);
pthread_rwlock_unlock(&rwlock); //释放写锁
Sleep(2000);
}
return NULL;
}
void* writerB(void* arg)
{
while(1)
{
pthread_rwlock_wrlock(&rwlock);
data++;
printf("B写者写入: %d\n",data);
pthread_rwlock_unlock(&rwlock);
Sleep(2000);
}
return NULL;
}
void main(int argc,char** argv)
{
pthread_rwlock_init(&rwlock, NULL); //初始化读写锁
pthread_create(&t1,NULL,readerM,NULL);
pthread_create(&t1,NULL,readerN,NULL);
pthread_create(&t2,NULL,writerA,NULL);
pthread_create(&t2,NULL,writerB,NULL);
pthread_rwlock_destroy(&rwlock); //销毁读写锁
Sleep(10000000);
return;
}
0 0