/* 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
linux读者写者问题
最新推荐文章于 2024-09-07 19:00:50 发布
该博客通过C代码展示了如何在Linux环境下实现读者写者问题。使用信号量和互斥锁来同步读写操作,确保了数据一致性。示例包括单读者单写者、多读者单写者和多读者多写者的场景。
摘要由CSDN通过智能技术生成