Chinaunix首页 | 论坛 | 博客
  • 博客访问: 535997
  • 博文数量: 142
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1452
  • 用 户 组: 普通用户
  • 注册时间: 2013-09-12 16:28
文章分类

全部博文(142)

文章存档

2016年(10)

2015年(60)

2014年(72)

我的朋友

分类: C/C++

2014-12-16 10:48:28


点击(此处)折叠或打开

  1. #include "../unipc.h"
  2. #include "pthread_rwlock.h"

  3. void rwlock_cancelrdwait(void *arg)
  4. {
  5.     my_pthread_rwlock_t *rw;

  6.     rw = (my_pthread_rwlock_t*)arg;
  7.     rw->rw_nwaitreaders--;
  8.     pthread_mutex_unlock(&rw->rw_mutex);
  9. }

  10. int my_pthread_rwlock_rdlock(my_pthread_rwlock_t *rw)
  11. {
  12.     int rc;

  13.     if(rw->rw_magic != RW_MAGIC)
  14.         return EINVAL;

  15.     rc = pthread_mutex_lock(&rw->rw_mutex);
  16.     if (rc != 0)
  17.         return rc;

  18.     while((rw->rw_refcount == -1) || (rw->rw_nwaitwriters > 0)) {
  19.         rw->rw_nwaitreaders++;
  20.         pthread_cleanup_push(rwlock_cancelrdwait,(void*)rw);
  21.         rc = pthread_cond_wait(&rw->rw_condreaders,&rw->rw_mutex);
  22.         pthread_cleanup_pop(0);
  23.         rw->rw_nwaitreaders--;
  24.     }
  25.     
  26.     rw->rw_refcount++;
  27.     pthread_mutex_unlock(&rw->rw_mutex);
  28.     return rc;
  29.     //pthread_cond_signal(&rw->rw_condwriters);
  30. }


点击(此处)折叠或打开

  1. #include "../unipc.h"
  2. #include "pthread_rwlock.h"

  3. void rwlock_cancelrdwait(void *arg)
  4. {
  5.     my_pthread_rwlock_t *rw;

  6.     rw = (my_pthread_rwlock_t*)arg;
  7.     rw->rw_nwaitreaders--;
  8.     pthread_mutex_unlock(&rw->rw_mutex);
  9. }

  10. int my_pthread_rwlock_rdlock(my_pthread_rwlock_t *rw)
  11. {
  12.     int rc;

  13.     if(rw->rw_magic != RW_MAGIC)
  14.         return EINVAL;

  15.     rc = pthread_mutex_lock(&rw->rw_mutex);
  16.     if (rc != 0)
  17.         return rc;

  18.     while((rw->rw_refcount == -1) || (rw->rw_nwaitwriters > 0)) {
  19.         rw->rw_nwaitreaders++;
  20.         pthread_cleanup_push(rwlock_cancelrdwait,(void*)rw);
  21.         rc = pthread_cond_wait(&rw->rw_condreaders,&rw->rw_mutex);
  22.         pthread_cleanup_pop(0);
  23.         rw->rw_nwaitreaders--;
  24.     }
  25.     
  26.     rw->rw_refcount++;
  27.     pthread_mutex_unlock(&rw->rw_mutex);
  28.     return rc;
  29.     //pthread_cond_signal(&rw->rw_condwriters);
  30. }


无论何时操作pthread_rwlock_t类型的结构,都必须给mutex上锁。
rw_refcount 等于-1表示写线程持有该读写锁,rw_nwaitwriters表示有线程正等着获取该读写锁的的一个写入锁,此时无法获取读写锁的一个读出锁。
阅读(476) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~