linux5.编写程序,利用多线程实现生产者-消费者问题,生产者和消费者分别在2个线程中,生产者生产的产品放在链表的表头上,消费者从表头取走产品。
时间: 2024-05-04 09:18:35 浏览: 24
以下是一个基本的生产者-消费者模型的多线程实现,使用了互斥锁和条件变量:
```c
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#define BUFFER_SIZE 10
typedef struct item_t {
int value;
struct item_t *next;
} item_t;
item_t *buffer = NULL;
pthread_mutex_t buffer_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t buffer_not_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t buffer_not_empty = PTHREAD_COND_INITIALIZER;
void *producer(void *arg) {
int i;
for (i = 0; i < BUFFER_SIZE * 2; i++) {
item_t *item = malloc(sizeof(item_t));
item->value = i;
pthread_mutex_lock(&buffer_mutex);
while (buffer != NULL && i % BUFFER_SIZE == 0) {
pthread_cond_wait(&buffer_not_full, &buffer_mutex);
}
item->next = buffer;
buffer = item;
pthread_cond_signal(&buffer_not_empty);
pthread_mutex_unlock(&buffer_mutex);
}
pthread_exit(NULL);
}
void *consumer(void *arg) {
int i;
for (i = 0; i < BUFFER_SIZE * 2; i++) {
pthread_mutex_lock(&buffer_mutex);
while (buffer == NULL) {
pthread_cond_wait(&buffer_not_empty, &buffer_mutex);
}
item_t *item = buffer;
buffer = item->next;
pthread_cond_signal(&buffer_not_full);
pthread_mutex_unlock(&buffer_mutex);
printf("Consuming item with value %d...\n", item->value);
free(item);
}
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 0;
}
```
在主函数中,我们创建了一个生产者线程和一个消费者线程。生产者线程循环生产一些项目,并将它们添加到缓冲区的开头。如果缓冲区已满,生产者会等待条件变量 `buffer_not_full`。一旦生产者添加了一个项目,它就会发出信号,通知消费者可以开始消费项目了。
消费者线程循环等待缓冲区中是否有项目可供消费。如果没有,它会等待条件变量 `buffer_not_empty`。一旦消费者开始消费项目,它会从缓冲区的头部删除项目,并发出信号,通知生产者可以继续生产新的项目。
需要注意的是,我们使用互斥锁来保护缓冲区的访问,以避免竞争条件。我们还使用条件变量来让线程在等待时休眠,并在等待的条件满足时被唤醒。这种方法比轮询缓冲区状态要更有效率,因为它可以让线程在等待时释放 CPU 时间片。
这只是一个基本的实现,你可以根据实际需求进行修改。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)