#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct msg {
struct msg *next;
int num;
};
struct msg *head = NULL;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *producer(void *p)
{
struct msg *mp;
for(;;)
{
mp = malloc(sizeof(struct msg));
mp->num = rand() % 2000 + 1;
printf("Producer %d\n",mp->num);
pthread_mutex_lock(&lock);
mp->next = head;
head = mp;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product);
sleep(rand() % 5);
}
return NULL;
}
void *consumer(void *p)
{
struct msg *mp;
for(;;)
{
pthread_mutex_lock(&lock);
while(head == NULL)
pthread_cond_wait(&has_product,&lock);
mp = head;
head = mp->next;
pthread_mutex_unlock(&lock);
printf("Consumer %d\n",mp->num);
free(mp);
sleep(rand() % 5);
}
return NULL;
}
int main()
{
pthread_t pid, cid;
srand(time(NULL));
pthread_create(&pid,NULL,producer,NULL);
pthread_create(&cid,NULL,consumer,NULL);
pthread_join(pid,NULL);
pthread_join(cid,NULL);
return 0;
}
生产者,消费者,pthread_cond_t pthread_mutex_t
生产者消费者模式
最新推荐文章于 2025-09-26 17:56:56 发布
本文介绍了一个使用多线程实现的生产者消费者模式示例。通过 C 语言中的 pthread 库来创建生产者线程和消费者线程。生产者不断地生成消息并将其添加到一个共享消息队列中;消费者则从该队列中取出并消费这些消息。为了确保线程间的同步,使用了互斥锁和条件变量。

767

被折叠的 条评论
为什么被折叠?



