写一个异步fifo代码
时间: 2023-04-03 16:01:06 浏览: 103
以下是一个简单的异步 FIFO 代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int read_ptr = , write_ptr = , count = ;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t not_full = PTHREAD_COND_INITIALIZER;
void put(int value) {
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) {
pthread_cond_wait(¬_full, &mutex);
}
buffer[write_ptr] = value;
write_ptr = (write_ptr + 1) % BUFFER_SIZE;
count++;
pthread_cond_signal(¬_empty);
pthread_mutex_unlock(&mutex);
}
int get() {
int value;
pthread_mutex_lock(&mutex);
while (count == ) {
pthread_cond_wait(¬_empty, &mutex);
}
value = buffer[read_ptr];
read_ptr = (read_ptr + 1) % BUFFER_SIZE;
count--;
pthread_cond_signal(¬_full);
pthread_mutex_unlock(&mutex);
return value;
}
void *producer(void *arg) {
int i;
for (i = ; i < 20; i++) {
put(i);
printf("producer put %d\n", i);
}
pthread_exit(NULL);
}
void *consumer(void *arg) {
int i, value;
for (i = ; i < 20; i++) {
value = get();
printf("consumer get %d\n", value);
}
pthread_exit(NULL);
}
int main() {
pthread_t producer_thread, consumer_thread;
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
return ;
}
阅读全文