读写者问题------读写锁
2016-04-24 14:47
344 查看
读写者问题是一类比较特殊的问题。可以允许多个读者同时读,但不允许多个写者或者写者和读者同时操作。所以需要保证读者和写者之间的同步与互斥关系,以及多个写者之间的互斥关系。
读写锁是一种自旋锁:自旋锁是当一个线程没有申请资源成功,不会等待,而是一直在进行循环判断是否锁被释放。
读写锁是一种自旋锁:自旋锁是当一个线程没有申请资源成功,不会等待,而是一直在进行循环判断是否锁被释放。
1 #include<stdio.h> 2 #include<pthread.h> 3 4 pthread_rwlock_t rwlock; 5 6 int buf; 7 void *reader(void *arg) 8 { 9 while(1) 10 { 11 pthread_rwlock_rdlock(&rwlock); 12 printf("reader%d is reading...:%d\n",(int)arg,buf); 13 pthread_rwlock_unlock(&rwlock); 14 sleep(1); 15 16 } 17 } 18 void *writer(void *arg) 19 { 20 int i = 0; 21 while(1) 22 { 23 pthread_rwlock_wrlock(&rwlock); 24 buf = i++; 25 printf("writer:%d\n",buf); 26 pthread_rwlock_unlock(&rwlock); 27 sleep(1); 28 } 29 } 30 31 int main() 32 { 33 pthread_t tid1,tid2,tid3,tid4; 34 pthread_create(&tid1,NULL,reader,(void*)1); 35 pthread_create(&tid3,NULL,reader,(void*)2); 36 pthread_create(&tid2,NULL,writer,NULL); 37 38 pthread_rwlock_init(&rwlock,NULL); 39 pthread_join(tid1,NULL); 40 pthread_join(tid3,NULL); 41 pthread_join(tid2,NULL); 42 pthread_rwlock_destroy(&rwlock); 43 return 0; 44 } 运行结果 [fbl@localhost rw_lock]$ ./rwlock writer:0 reader2 is reading...:0 reader1 is reading...:0 writer:1 reader2 is reading...:1 reader1 is reading...:1 writer:2 reader2 is reading...:2 reader1 is reading...:2 writer:3 reader2 is reading...:3 reader1 is reading...:3 writer:4 reader2 is reading...:4 reader1 is reading...:4 writer:5 reader2 is reading...:5 reader1 is reading...:5 writer:6 reader2 is reading...:6 reader1 is reading...:6
相关文章推荐
- 如何将八进制转换为二进制、十进制、十六进制
- Android studio修改debug.keystore
- c#中using的用法详解
- 机器学习中的范数与距离
- STL 去重排序
- 2016.4.24 little_bai_开始记录Android学习心得,我不太确定自己的方向,但是希望走的远些。
- http-关于application/x-www-form-urlencoded等字符编码的解释说明
- 安装和配置Sentry(收录)
- [bzoj4518] [Sdoi2016]征途
- Stringbuffer和Stringbuilder
- 北京林业大学“计蒜客”杯程序设计竞赛 网络赛 G. 易彰彪的一张表 (KMP)
- java之多线程
- HashMap源码注解 之 resize()方法(七)
- PHP垃圾回收机制的理解
- 50. Pow(x, n) 【M】【62】
- python的list由多个tuple组成,如何返回每个tuple的每个元素
- uva 562 Dividing coins
- 数据结构算法3_2 迷宫求解
- 微课播放器
- 由于调用了interrupt方法,所以抛出了InterruptedException异常