/*
硬件fifo
1 是环形buff
2 是根据时钟判断是否为满 (根据时钟差)
3 同步 读和写 ???
*/
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#define//一个 block 多少个数据 (char)
#define//多少个block
#define// fifo 里面有多少个数据 (char)
int num;
int update_full(void);
char fifobuf[TOTOL_SIZE]={0};
int totol_write_num =0; //共发生过多少 写时钟
int totol_read_num=0; //共发生过多少 读时钟
int available_block =0; // 写时钟与读时钟之间差距
static pthread_t thread; // 线程
static pthread_cond_t cond_write; // 写 信号量
static pthread_mutex_t mutex_write; // 互斥锁
static pthread_cond_t cond_read; // 读 信号量
static pthread_mutex_t mutex_read; // 互斥锁
char readbuf[SIZE+1]={0};
int states; // 状态
enum
{
FULL = 0,
NOTFULL,
};
enum
{
MEPTY = 0,
NOTMEPTY,
};
int is_full_block(int i) //判断是否是一个 block
{
if((i+1)%SIZE==0)
{
++totol_write_num; // 写 block + 1
update_full(); // 更新 full 状态
return 1; // block
}
else
return 0;
}
int update_full() // 判断当前是否为full状态 (totol_write_num 永远大于 totol_read_num,因为同步所以永远会大于等于)
{
if(SIZE <= (totol_write_num - totol_read_num))
{
states = FULL;
}
else
states = NOTFULL;
printf("update_full is %d\n",states);
return states;
}
int updat_mepty()
{
if(0 == (totol_write_num - totol_read_num))
states = MEPTY;
else
states = NOTMEPTY;
return states;
}
void * thr_fn(void * arg)
{
while(1)
{
pthread_mutex_lock(&mutex_write); //获取锁
printf("*****\n");
pthread_cond_wait(&cond_write, &mutex_write); //无数据就休眠,有数据被唤醒
for(;available_block>0;available_block--)
{
sleep(2);
num=totol_read_num%SIZE;
memcpy(readbuf,(fifobuf+SIZE*num),SIZE);
pthread_cond_signal(&cond_read); //唤醒 因为 full状态而进入休眠的 写线程
printf("thread b send %s\n",readbuf); //以 block为单位输出
++totol_read_num;
}
pthread_mutex_unlock(&mutex_write); //释放锁
}
}
int main()
{
char value;
int i=0;
totol_read_num = 0;
pthread_mutex_init(&mutex_write, NULL); //初始化互斥锁
pthread_cond_init(&cond_write, NULL); //初始化信号量
pthread_mutex_init(&mutex_read, NULL); //初始化互斥锁
pthread_cond_init(&cond_read, NULL); //初始化信号量
if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) {
printf("error when create pthread,%d\n", errno);
return 1;
}
while(1)
{
if(FULL!=update_full()) // 非full 状态进行数据读取
{
printf("is not full\n");
while ((value=getchar())=='\n'); // 读取标准输入 读取数据
printf("value is %c\n",value);
fifobuf[i] = value; // 输入 fifo
//printf("i Is %d\n",i);
if(1==is_full_block(i)) // 如果是一个 block
{
//printf("is lock before");
pthread_mutex_lock(&mutex_write);
++available_block; //多少 block 需要处理
//printf("available_block is %d\n",available_block);
pthread_cond_signal(&cond_write); //发出的 cond 如果没有睡眠的捕捉器,捕捉就会丢失掉
pthread_mutex_unlock(&mutex_write); //唤醒读线程
}
i = (i+1) % TOTOL_SIZE;
}
else //休眠当 是 full 状态
{
printf("thread main sleep\n");
pthread_mutex_lock(&mutex_read);
pthread_cond_wait(&cond_read, &mutex_read); //等待信号量唤醒
pthread_mutex_unlock(&mutex_read);
printf("thread main sleep exit\n");
}
}
}