linux 多线程 其中一个写 一个读加锁,Linux多线程编程之读写锁

本文通过示例代码详细介绍了读写锁的概念及其在多线程中的作用。读写锁允许多个线程同时读取资源,但在写入时保持独占,确保数据一致性。系统在分配锁时优先考虑写锁,导致读锁可以并行执行,而写锁会阻塞其他读写操作。文章还讨论了读写锁与互斥量和条件变量的关系,并提出后续将探讨如何实现读写锁。
摘要由CSDN通过智能技术生成

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

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

#include

#include

#include

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

#include

#include

#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

{

pthread_create(&tid_ar[i], NULL, thread_fun_ar2, &i);

sleep(1);

}

pthread_join(tid, NULL);

for(int i=0;i

{

pthread_join(tid_ar[i], NULL);

}

return 0;

}

运行的结果

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值