#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#define SIZE 4 //一个 block 多少个数据
#define BLOCK 4
#define TOTOL_SIZE (SIZE*BLOCK)
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; //非 block
}
int update_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--)
{
pthread_cond_signal(&cond_read);
sleep(2);// moni xie kuai du man
num=totol_read_num%SIZE;
memcpy(readbuf,(fifobuf+SIZE*num),SIZE);
printf("thread b send %s\n",readbuf);
++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())
{
printf("is not full\n");
while ((value=getchar())=='\n');
printf("value is %c\n",value);
fifobuf[i] = value;
//printf("i Is %d\n",i);
if(1==is_full_block(i))
{
//printf("is lock before");
pthread_mutex_lock(&mutex_write);
//printf("is lock after");
++available_block; //多少 block 需要处理
//printf("available_block is %d\n",available_block);
pthread_cond_signal(&cond_write); //发出的 cond 如果没有睡眠的捕捉器,捕捉就会丢失掉
//printf("cond_write after\n");
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");
}
}
}
2021-04-01
Guess you like
Origin blog.csdn.net/aningxiaoxixi/article/details/115365530
Recommended
Ranking