读写锁
来源:互联网 发布:mac任务管理器怎么打开 编辑:程序博客网 时间:2024/06/18 14:34
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> static int count=0; pthread_rwlock_t rwlock=PTHREAD_RWLOCK_INITIALIZER; void *fun_rd(void *data) { char *thd_name=(char *)data; while(1) { pthread_rwlock_rdlock(&rwlock); printf("线程%s进入临界区:%d\n",thd_name,count); sleep(1); printf("线程%s离开临界区。\n",thd_name); pthread_rwlock_unlock(&rwlock); sleep(1);} } void *fun_wr(void *data) { char *thd_name=(char *)data; while(1) { pthread_rwlock_wrlock(&rwlock); printf("线程%s进入临界区:%d\n",thd_name,++count); sleep(1); printf("线程%s离开临界区。\n",thd_name); pthread_rwlock_unlock(&rwlock); sleep(2); } } int main() { pthread_t tid_rd_first,tid_rd_second,tid_wr_first,tid_wr_second;pthread_create(&tid_rd_first,NULL,fun_rd,"read_1");pthread_create(&tid_rd_second,NULL,fun_rd,"read_2");pthread_create(&tid_wr_first,NULL,fun_wr,"write_1");pthread_create(&tid_wr_second,NULL,fun_wr,"write_2");pthread_join(tid_wr_first,NULL);pthread_rwlock_destroy(&rwlock); return 0; }
输出:
转载:http://www.cnblogs.com/yuuyuu/p/5143881.html