Linux多线程──读者写者问题

读者写者问题

这也是一个非常经典的多线程题目,题目大意如下:有一个写者很多读者,多个读者可以同时读文件,但写者在写文件时不允许有读者在读文件,同样有读者读时写者也不能写。

程序:

// reader_writer.cpp
//
// 读者写者问题
// 有一个写者很多读者,多个读者可以同时读文件,但写者在写文件时不允许有读者在读文件,
// 同样有读者读时写者也不能写。
//

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

// 定义数据类
class data
{
public:
    data(int i, float f):
        I(i), F(f)
    {}

    int I;
    float F;
};

// 读者写者读写的内容
data *p_data = NULL;

pthread_rwlock_t lock;

// 写者数目
const int WRITER_NUMBER = 2;

void *reader(void *arg);
void *writer(void *arg);

int main(int argc, char **argv)
{
    pthread_t reader_tid;
    pthread_t writer_tid[WRITER_NUMBER];
    
    pthread_create(&reader_tid, NULL, reader, NULL);
    for (int i = 0; i < WRITER_NUMBER; ++i)
    {
        pthread_create(&writer_tid[i], NULL, writer, (void *)i);
    }

    sleep(1);
    
    return 0;
}

void *reader(void *arg)
{
    int id = (int)arg;

    pthread_detach(pthread_self());
    
    while (true)
    {
        pthread_rwlock_rdlock(&lock);
        printf("reader %d is reading the data; ", id);
        if (p_data == NULL)
        {
            printf("the data is NULL\n");
        }
        else
        {
            printf("the data is (%d, %f)\n", p_data->I, p_data->F);
        }
        pthread_rwlock_unlock(&lock);
    }
    return (void *)0;
}

void *writer(void *arg)
{
    pthread_detach(pthread_self());

    while (true)
    {
        pthread_rwlock_wrlock(&lock);
        printf("writer is writing the data; ");
        if (p_data == NULL)
        {
            p_data = new data(1, 1.1f);
            printf("writer create the data (%d, %f)\n", p_data->I, p_data->F);
        }
        else
        {
            delete p_data;
            p_data = NULL;
            printf("writer free the data\n");
        }
        pthread_rwlock_unlock(&lock);
    }
    return (void *)0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值