您的位置:首页 > 其它

线程条件变量应用(消费者和生产着模型)

2013-11-05 21:16 369 查看
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.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 *consumer(void *p)
{
struct msg *mp = NULL;
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);
}
}

void *producer(void *p)
{
struct msg *mp = NULL;
for(;;)
{
mp = malloc(sizeof(*mp));
pthread_mutex_lock(&lock);
mp->next = head;
mp->num = rand()%1000;
head = mp;
printf("Produce %d\n",mp->num);
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product);
sleep(rand() % 5);
}
}

int main(void)
{
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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: