使用线程的互斥锁实现生产者消费者模型

#include 【使用线程的互斥锁实现生产者消费者模型】#include #include #include #include #include #include #define PTHREAD_NUM 2typedef void *(*pthread_func_t)(void *); struct product{ int num; struct product *next; }*head, *goods = NULL; pthread_mutex_t mutex; pthread_cond_tcond; static int g_count = 0; void *producer(void *arg) { int i = 0; while(1) { goods = (struct product *)malloc(sizeof(struct product)); if(NULL == goods) { perror("malloc"); return (void *)NULL; } pthread_mutex_lock(&mutex); goods -> num = i; printf("producer--------g_count %d = %d\n", g_count, goods->num); i++; goods -> next = head -> next; head -> next = goods; pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cond); sleep(1); //g_count++; if (g_count == 5) break; g_count++; } pthread_exit((void *)NULL); }void *consumer(void *arg) { int i = 0; sleep(3); while(1) { pthread_mutex_lock(&mutex); while(head->next == NULL) { pthread_cond_wait(&cond,&mutex); }struct product *temp = head -> next; head -> next = temp -> next; printf("consumer------------g_count %d = %d\n", g_count, temp->num); i++; free(temp); pthread_mutex_unlock(&mutex); if (g_count == 5) break; } pthread_exit((void *)NULL); }int main(int argc, char const *argv[]) { int i = 0,ret; void * retval[PTHREAD_NUM]; pthread_t tid[PTHREAD_NUM]; head = (struct product *)malloc(sizeof(struct product *)); if(NULL == head) { perror("malloc"); return -1; } head -> next = NULL; pthread_mutex_init(&mutex,NULL); pthread_cond_init(&cond,NULL); pthread_func_t pth_func[PTHREAD_NUM] = {producer, consumer}; for(; i < PTHREAD_NUM; i++) { ret = pthread_create(&tid[i], NULL, pth_func[i], NULL); } for(i = 0; i < PTHREAD_NUM; i++) { pthread_join(tid[i], &retval[i]); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; }

测试结果 使用线程的互斥锁实现生产者消费者模型
文章图片

    推荐阅读