语言实现生产者消费者
时间: 2024-03-31 07:30:37 浏览: 27
生产者消费者模型是一种常见的并发编程模式,用于解决生产者和消费者之间的数据交互问题。该模型包括生产者、消费者和一个缓冲区,生产者将数据放入缓冲区,消费者从缓冲区取出数据进行处理。
以下是两种语言实现生产者消费者模型的例子:
1. Golang实现生产者消费者模型[^1]:
```go
package main
import (
"fmt"
"time"
)
func producer(ch chan<- int) {
for i := 0; i < 5; i++ {
ch <- i
fmt.Println("Producer produced:", i)
time.Sleep(time.Second)
}
close(ch)
}
func consumer(ch <-chan int) {
for num := range ch {
fmt.Println("Consumer consumed:", num)
time.Sleep(time.Millisecond * 500)
}
}
func main() {
ch := make(chan int, 3)
go producer(ch)
consumer(ch)
}
```
2. C语言实现生产者消费者模型[^2]:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
void *producer(void *arg) {
int item;
for (int i = 0; i < 5; i++) {
item = rand() % 100; // 产生随机数作为数据
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[in] = item;
printf("Producer produced: %d\n", item);
in = (in + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(1);
}
pthread_exit(NULL);
}
void *consumer(void *arg) {
int item;
for (int i = 0; i < 5; i++) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
item = buffer[out];
printf("Consumer consumed: %d\n", item);
out = (out + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
usleep(500000);
}
pthread_exit(NULL);
}
int main() {
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
pthread_t producerThread, consumerThread;
pthread_create(&producerThread, NULL, producer, NULL);
pthread_create(&consumerThread, NULL, consumer, NULL);
pthread_join(producerThread, NULL);
pthread_join(consumerThread, NULL);
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
```