c语言编程使用线程和信号量、PV操作 实现生产者-消费者模型
时间: 2024-05-10 21:17:49 浏览: 386
生产者-消费者模型是一个经典的并发编程问题,可以使用线程和信号量、PV操作来实现。下面是一个基于C语言的生产者-消费者模型的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int buffer_index;
pthread_mutex_t buffer_mutex;
sem_t full_sem, empty_sem;
void insert(int item) {
buffer[buffer_index++] = item;
}
int remove_item() {
return buffer[--buffer_index];
}
void *producer(void *param) {
int item;
while (1) {
item = rand() % 100; // 产生随机数
sem_wait(&empty_sem);
pthread_mutex_lock(&buffer_mutex);
insert(item);
pthread_mutex_unlock(&buffer_mutex);
sem_post(&full_sem);
printf("Producer produced %d\n", item);
}
}
void *consumer(void *param) {
int item;
while (1) {
sem_wait(&full_sem);
pthread_mutex_lock(&buffer_mutex);
item = remove_item();
pthread_mutex_unlock(&buffer_mutex);
sem_post(&empty_sem);
printf("Consumer consumed %d\n", item);
}
}
int main(int argc, char *argv[]) {
pthread_t producer_thread, consumer_thread;
pthread_mutex_init(&buffer_mutex, NULL);
sem_init(&full_sem, 0, 0);
sem_init(&empty_sem, 0, BUFFER_SIZE);
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
pthread_mutex_destroy(&buffer_mutex);
sem_destroy(&empty_sem);
sem_destroy(&full_sem);
return 0;
}
```
在上面的代码中,我们定义了一个大小为10的缓冲区(数组),然后使用一个整数`buffer_index`来表示缓冲区中已有的元素个数。我们还定义了一个互斥锁`buffer_mutex`和两个信号量`full_sem`和`empty_sem`,其中`full_sem`表示缓冲区中已有的元素个数,`empty_sem`表示缓冲区还能容纳的元素个数。
生产者线程在每次生产一个元素后,将它插入到缓冲区中,并发送一个`full_sem`信号量,表示缓冲区中已有的元素个数加1。消费者线程在每次消费一个元素后,将它从缓冲区中移除,并发送一个`empty_sem`信号量,表示缓冲区还能容纳的元素个数加1。
需要注意的是,我们在使用互斥锁和信号量时,要注意它们的加锁和解锁的顺序,否则可能会出现死锁等问题。在上面的代码中,我们先使用`sem_wait`函数来等待信号量,然后再使用`pthread_mutex_lock`函数来加锁互斥锁;同样地,在解锁时,也要先使用`pthread_mutex_unlock`函数来解锁互斥锁,然后再使用`sem_post`函数来发送信号量。
阅读全文
相关推荐
















