上一节实现了键盘驱动程序,每按一个键,都打印出来。
本节实现一个环形缓冲区,来作为键盘输入的缓冲。
缓冲区要有的功能:
- 同一时刻只能被一个生产者或消费者使用(互斥);–锁来实现
- 缓冲区满时,生产者不能往缓冲区添加数据;
- 缓冲区空时,消费者不能从缓冲区取数据。
ioqueue.h
#ifndef __DEVICE_IOQUEUE_H
#define __DEVICE_IOQUEUE_H
#include "../lib/std_int.h"
#include "../thread/thread.h"
#include "../thread/sync.h"
#define NULL ((void*)0)
#define bool int
#define bufsize 64
/* 环形队列 */
struct ioqueue {
// 生产者消费者问题
struct lock lock;
/* 生产者,缓冲区不满时就继续往里面放数据,
* 否则就睡眠,此项记录哪个生产者在此缓冲区上睡眠。*/
struct task_struct* producer;
/* 消费者,缓冲区不空时就继续从往里面拿数据,
* 否则就睡眠,此项记录哪个消费者在此缓冲区上睡眠。*/
struct task_struct* consumer;
char buf[bufsize]; // 缓冲区大小
int32_t head; // 队首,数据往队首处写入
int32_t tail; // 队尾,数据从队尾处读出
};
void ioqueue_init(struct ioqueue* ioq);
bool ioq_full(struct ioqueue* ioq);
char ioq_getchar(struct ioqueue* ioq);
void ioq_putchar(struct ioqueue* ioq, char byte);
#endif
ioqueue.c
#include