C语言 一种与互斥锁同步读取和修改的方法



我正在实现Web代理服务器缓存的同步。有两种情况:

  1. 如果缓存正在被修改,则无法被其他人修改 线程
  2. 如果正在读取缓存,则无法由其他人修改 线程,但它可以被其他线程读取。

我想使缓存可读,即使它正在被其他线程读取。

int readflag = 0;
// read
void read()
{
pthread_mutex_lock();
pthread_mutex_unlock();
++readflag;
/* read the cache*/
--readflag;
}
// modify
void write()
{
while(readflag > 0);
pthread_mutex_lock();
/* modify the cache*/
pthread_mutex_unlock();
}

这是我的简单代码。但是,它看起来很尴尬,也不是线程安全的。 如何实现此同步?

Pthreads 为此提供了读写锁。

使用 pthreads 读写锁的示例:

#include <pthread.h>
#include <assert.h>
static pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
static void read()
{
int r;
r=pthread_rwlock_rdlock(&rwlock); 
assert(0==r); 
//lock/unlock ops can't fail
//unless your program's logic is flawed
/* read the cache*/
r=pthread_rwlock_unlock(&rwlock); assert(0==r);
}
// modify
static void write()
{
int r;
r=pthread_rwlock_wrlock(&rwlock); assert(0==r);
/* modify the cache*/
r=pthread_rwlock_unlock(&rwlock); assert(0==r);
}

最新更新