在rwlock中使用pthread条件变量 [英] Using pthread condition variable with rwlock

查看:111
本文介绍了在rwlock中使用pthread条件变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在C ++中将 pthread rwlock 结构与条件例程一起使用的方法.

I'm looking for a way to use pthread rwlock structure with conditions routines in C++.

我有两个问题:

首先:怎么可能?如果不能,为什么?

First: How is it possible and if we can't, why ?

第二:为什么当前的POSIX pthread尚未实现此行为?

Second: Why current POSIX pthread have not implemented this behaviour ?

为了理解我的目的,我解释了我的用途:我有一个生产者-消费者模型处理一个共享数组.当数组为空时,使用者将cond_wait,但在读取某些elems时将使用rdlock.当从数组中添加(+信号)或删除元素时,生产者将陷入困境.

To understand my purpose, I explain what will be my use: I've a producer-consumer model dealing with one shared array. The consumer will cond_wait when the array is empty, but rdlock when reading some elems. The producer will wrlock when adding(+signal) or removing elems from the array.

使用rdlock代替Mutex_lock的好处是提高了性能:使用Mutex_lock时,多个读取器将阻止,而使用rdlock,则多个读取器将不会阻止.

The benefit of using rdlock instead of mutex_lock is to improve performance: when using mutex_lock, several readers would block, whereas using rdlock several readers would not block.

推荐答案

我假设条件"是指条件变量".他们是不同的东西.

I assume that by "conditions", you mean "conditional variables". They're different things.

否,在等待条件变量时不能使用rwlock.我无法回答为什么",但这就是POSIX决定这样做的方式.也许只是为了使事情简单.

No, you cannot use a rwlock when waiting on a conditional variable. I cannot answer as to the "why", but that's the way POSIX has decided to do it. Perhaps just to keep things simple.

但是,通过仅使用互斥锁和2个条件变量而不使用POSIX rwlock来创建自己的rwlock类,您仍然可以获得所需的行为:

You can still get the behavior you want, however, by making your own rwlock class by using only a mutex and 2 conditional variables without using a POSIX rwlock:

getReadLock():
     lock(mutex)
     while(array.empty())
         wait(readersCondVar, mutex)
     readers++;
     unlock(mutex)       

releaseReadLock():
     lock(mutex)
     if (--readers == 0)
           broadcast(writerCondVar, mutex) // or signal, if only 1 producer
     unlock(mutex)

readerThread:
     forever() {
         getReadLock()
         read()
         releaseReadLock()
      }

getWriteLock():
     lock(mutex)
     while(readers) {
         wait(writerCondVar, mutex)
     }

releaseWriteLock():
     broadcast(readersCondVar, mutex)
     unlock(mutex)

writerThread():
      forever() {
         getWriteLock()
         write()
         releaseWriteLock()
      }

简单,随心所欲.

这篇关于在rwlock中使用pthread条件变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆