您的位置:首页 > 其它

使用读写锁解决读者-写者问题

2015-07-08 22:38 381 查看

读写锁

读写锁适合于对数据结构的读次数比写次数多得多的情况.因为,读模式锁定时可以共享,以写 模式锁住时意味着独占,所以读写锁又叫共享-独占锁.

初始化和销毁:

#include <pthread.h>
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const
pthread_rwlockattr_t *restrict attr);
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);

成功则返回0,出错则返回错误编号. 同互斥量以上,在释放读写锁占用的内存之前,需要先通过 pthread_rwlock_destroy对读写锁进行清理工作, 释放由init分配的资源.

读和写:

#include <pthread.h>
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);

成功则返回0,出错则返回错误编号.这3个函数分别实现获取读锁,获取写锁和释放锁的操作.获 取锁的两个函数是阻塞操作,同样,非阻塞的函数为:

#include <pthread.h>
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);

成功则返回0,出错则返回错误编号.非阻塞的获取锁操作,如果可以获取则返回0,否则返回 错误的EBUSY.

代码:

/*********    说明:
*********    读写锁适合于对数据结构的读次数比写次数多得多的情况.因为,
********     读模式锁定时可以共享,以写 模式锁住时意味着独占,所以读写锁又叫共享-独占锁.
********     要让读者与写者之间、以及写者与写者之问要互斥地访同数据集;
*********/

#include <pthread.h>
#include <signal.h>
#include <stdio.h>
//#include "apue.h"

#define R 5 // reader NO.
#define W 5 // reader and writer NO.

pthread_rwlock_t lock; //it's mean writer can writing

int readCount = 0;

void* reader(void *arg)
{
int n = W;
int id = *(int*)arg;
while (n--)
{
sleep( rand() % 3 );
pthread_rwlock_rdlock(&lock);
printf("reader %d is reading\n", id);
sleep( rand() % 3 );

pthread_rwlock_unlock(&lock);
printf("reader %d is leaving\n", id);
}
printf("----reader %d has done----\n", id);
}

void* writer(void *arg)
{
int n = W;
while (n--)
{
sleep( rand() % 3 );
pthread_rwlock_wrlock(&lock);
printf("\twriter is writing\n");
sleep( rand() % 3 );
pthread_rwlock_unlock(&lock);
printf("\twriter is leaving\n");
}
printf("----writer has done----\n");
}

int main(int argc, const char *argv[])
{
int err;
pthread_t tid[R], writerTid;
int i;

err = pthread_create(&writerTid, NULL, writer, (void *)NULL);
if (err != 0)
{
printf("can't create process for writer\n");
}

pthread_rwlock_init(&lock, NULL);
for (i = 0; i < R; i++)
{
err = pthread_create(&tid[i], NULL, reader, &i);
if (err != 0)
{
printf("can't create process for reader");
}
}
while(1);
pthread_rwlock_destroy(&lock);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: