C语言实现循环缓冲区,并交替访问缓冲区,进行数据读取操作。
线程交替执行使用信号量,对应的头文件为 #include <semaphore.h>
关键代码如下main.c
int main()
{
//初始化信号量
sem_init(&semA,0,1);
sem_init(&semB,0,0);
sem_init(&semC,0,0);
fp1 = fopen("./data/writeData.txt", "wb");
fp2 = fopen("./data/readData.txt", "wb");
initRingbuffer();
pthread_t tid[3];
//创建线程
pthread_create(&tid[0], NULL, &func1, NULL);//线程:向缓冲区中写数据
pthread_create(&tid[1], NULL, &func2, NULL);//线程:从缓冲区中读数据
pthread_create(&tid[2], NULL, &func3, NULL);//线程:从缓冲区中读数据
//等待
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_join(tid[2], NULL);
while (1)
{
printf("%d:main\n", ++num);
sleep(1);
}
fclose(fp1);
fclose(fp2);
return 0;
}
运行结果如下:
完整工程下载