linux读者写者问题

该博客通过C代码展示了如何在Linux环境下实现读者写者问题。使用信号量和互斥锁来同步读写操作,确保了数据一致性。示例包括单读者单写者、多读者单写者和多读者多写者的场景。
摘要由CSDN通过智能技术生成
/* Copy right(c) 2014
 * All rights reserved
 * http://blog.csdn.net/ezhou_liukai
 */

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

const int QUEUE_LEN = 10;    //Length of circular queue
int g_nArrQueue[QUEUE_LEN];  //circular queue
int g_ni, g_nj;
int g_nDataR, g_nDataW;

sem_t g_sem_full, g_sem_empty;
pthread_mutex_t g_mutex_reader, g_mutex_writer;

void *ReaderThreadFun(void *arg)
{
    printf("The ID:%u of reader starts to read the datas\n", (unsigned int)pthread_self());
    
    int nDataR = 0;
    while (nDataR < 20)
    {
    	sem_wait(&g_sem_full);
        nDataR = g_nArrQueue[g_ni];
    	g_ni = (g_ni + 1)%QUEUE_LEN;
    	printf("The ID:%u of reader reads the data:%d from circular queue\n", (unsigned int)pthread_self(), nDataR);
    	sem_post(&g_sem_empty);
    }

    printf("The ID:%u of reader ends to read the datas\n", (unsig
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值