码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-07-09 00:28:06      阅读:357      评论:0      收藏:0      [点我收藏+]

标签:

读写锁

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

初始化和销毁:

#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;
}

读写锁是一种写优先的互斥锁.

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

标签:

原文地址:http://www.cnblogs.com/biglucky/p/4631582.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!