Linux之信号量 | 消费者生产者模型的循环队列
#include <stdio.h>
#include <stdlib.com>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 10
typedef struct {
int buffer[BUFFER_SIZE];
sem_t empty_count;
sem_t full_count;
sem_t mutex;
int read_pos, write_pos;
} CircularQueue;
CircularQueue q;
void init_queue(CircularQueue *q) {
q->read_pos = 0;
q->write_pos = 0;
sem_init(&q->empty_count, 0, BUFFER_SIZE);
sem_init(&q->full_count, 0, 0);
sem_init(&q->mutex, 0, 1);
}
void enqueue(CircularQueue *q, int data) {
sem_wait(&q->empty_count);
sem_wait(&q->mutex);
q->buffer[q->write_pos] = data;
q->write_pos = (q->write_pos + 1) % BUFFER_SIZE;
sem_post(&q->mutex);
sem_post(&q->full_count);
}
int dequeue(CircularQueue *q) {
int data;
sem_wait(&q->full_count);
sem_wait(&q->mutex);
data = q->buffer[q->read_pos];
q->read_pos = (q->read_pos + 1) % BUFFER_SIZE;
sem_post(&q->mutex);
sem_post(&q->empty_count);
return data;
}
int main() {
init_queue(&q);
// 生产者消费者线程...
return 0;
}
这个代码实例提供了一个使用信号量实现的循环队列的简单示例。初始化队列,入队操作和出队操作都被正确地实现,并且使用了适当的信号量来同步访问。这个例子可以作为在Linux环境下实现线程同步和通信的一个基础教学示例。
评论已关闭