
点击(此处)折叠或打开
- /*
- * produce_consumer.c
- *
- * Created on: Oct 24, 2012
- * Author: hl
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <string.h>
- #include <unistd.h>
-
- //消息头
- struct msg
- {
- int num;
- struct msg * next;
- };
- struct msg * head;
-
- pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /// < 互斥锁
- pthread_cond_t cond = PTHREAD_COND_INITIALIZER; /// < 唤醒机制
-
- /**
- * @brief 消费者
- * @param 修改:
- * - 打算从尾部消费(否则较早生产的总是消费不到,过期了!)
- */
- void * consumer(void * pVoid)
- {
- struct msg * mp;
- struct msg * mpp;
- while (1)
- {
- pthread_mutex_lock(&mutex);
- if (NULL == head)
- pthread_cond_wait(&cond, &mutex);
- mp = head;
- if (mp->next) /// < 超过一个结点
- {
- while (mp->next)
- {
- mpp = mp; /// < 前一个
- mp = mp->next; /// < 链表最后一个
- }
- printf("Consume %d\n", mp->num);
- free(mp);
- mpp->next = mp = NULL; /// < 必须的,且注意mpp->next!
- }
- else /// < 只有头结点的情况
- {
- printf("Consume %d\n", mp->num);
- free(mp);
- head = mp = NULL; /// < 必须的,且注意head!
- }
- pthread_mutex_unlock(&mutex);
- sleep(2);
- }
- return pVoid;
- }
-
- /**
- * @brief 生产者
- */
- void * producer(void * pVoid)
- {
- struct msg * mp;
- while (1)
- {
- mp = (struct msg *)malloc(sizeof(struct msg));
- mp->num = rand()%1000 + 1;
- printf("Produce %d\n", mp->num);
- pthread_mutex_lock(&mutex);
- mp->next = head;
- head = mp;
- pthread_mutex_unlock(&mutex);
- pthread_cond_signal(&cond);
- sleep(1);
- }
- return pVoid;
- }
-
-
-
- int main(void)
- {
- pthread_t pid;
- pthread_t cid;
-
- head = NULL;
-
- int err;
- err = pthread_create(&pid, NULL, producer, "producer");
- if (0 != err)
- {
- fprintf(stderr, "create thread1 failed:----!%s\n", strerror(err));
- return -1;
- }
-
- err = pthread_create(&cid, NULL, consumer, "consumer");
- if (0 != err)
- {
- fprintf(stderr, "create thread2 failed:----!%s\n", strerror(err));
- return -1;
- }
- pthread_join(pid, NULL);
- pthread_join(cid, NULL);
-
- return 0;
- }