Linux多线程编程之读写锁

读写锁也是线程同步中的一种同步机制,简单的来说:读写锁既有读的方面也有写的方面,其中读是共享锁,而写是独占锁,而且系统中读写锁的分配是写锁优先的。

下面的用例,证明了读锁是共享锁。

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
void*thread_fun1(void *arg)
{
    pthread_rwlock_rdlock(&rwlock);
    printf("This is fun 1.\n");
    //pthread_rwlock_unlock(&rwlock);
}
void*thread_fun2(void *arg)
{
    pthread_rwlock_rdlock(&rwlock);
    printf("This is fun 2.\n");
    pthread_rwlock_unlock(&rwlock);
}


int main()
{
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, thread_fun1, NULL);
    sleep(2);
    pthread_create(&tid2, NULL, thread_fun2, NULL);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    return 0;
}
运行的结果

thread_fun1中加了读锁,但并没有解读锁;thread_fun2中也可以加读锁执行

如果thread_fun2中加的是写锁,则不能执行。因为有线程加了读锁却并没有解锁,所以写锁难以分配,线程难以执行。

如果thread_fun1中加的也是写锁,那么只要thread_fun1没有执行完,thread_fun2的写锁难以分配。所以只有thread_fun1执行完了之后,thread_fun2才可以执行。

下面的用例证明了系统的读写锁分配是写锁分配优先的:

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

#define THREAD_NUM 5
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
void* thread_fun(void *arg)
{
    pthread_rwlock_wrlock(&rwlock);
    printf("thread fun lock write lock.\n");
    sleep(10);
    pthread_rwlock_unlock(&rwlock);
    printf("thread fun lock write unlock.\n");
    printf("thread fun end.\n");
}
void*thread_fun_ar1(void *arg)
{
    int index = *(int *)arg;
    printf("[%d] thread start up.\n",index);
    pthread_rwlock_rdlock(&rwlock);
    printf("[%d] thread rdlock\n",index);
    pthread_rwlock_unlock(&rwlock);
}
void*thread_fun_ar2(void *arg)
{
    int index = *(int *)arg;
    printf("[%d] thread start up.\n",index);
    pthread_rwlock_wrlock(&rwlock);
    printf("[%d] thread wrlock\n",index);
    pthread_rwlock_unlock(&rwlock);
}



int main()
{
    pthread_t tid;
    pthread_create(&tid, NULL, thread_fun, NULL);
    sleep(1);
    pthread_t tid_ar[THREAD_NUM];
    for(int i=0;i<2;++i)
    {
        pthread_create(&tid_ar[i], NULL, thread_fun_ar1, &i);
        sleep(1);
    }
    for(int i=2;i<THREAD_NUM;++i)
    {
        pthread_create(&tid_ar[i], NULL, thread_fun_ar2, &i);
        sleep(1);
    }
    pthread_join(tid, NULL);
    for(int i=0;i<THREAD_NUM;++i)
    {
        pthread_join(tid_ar[i], NULL);
    }
    return 0;
}
运行的结果

我们先给一个进程分配写锁,用循环创建的其他进程都将被阻塞。调用sleep()函数延时,使得循环创建的五个进程都处于启动状态,然后解写锁。五个进程中有的要分配写锁,有的要分配读锁。多次执行程序,从运行的结果可以看出系统是优先分配写锁的。


 据说用互斥量和条件量,可以实现读写锁。ennnnnnnn后续要完成的任务。

猜你喜欢

转载自blog.csdn.net/qq_35353824/article/details/88790260
今日推荐