c pthread_cond_t demo
// // Created by gxf on 2020/3/24. // #include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; typedef struct ListNode_S{ int data; struct ListNode_S *next; }node; node *head = NULL; void consumer() { while (1) { pthread_mutex_lock(&lock); while (NULL == head) { printf("in consumer head is null\n"); pthread_cond_wait(&cond, &lock); } node *tmp = head; head = head->next; printf("consumer data:%d\n", tmp->data); free(tmp); pthread_mutex_unlock(&lock); } } int main() { pthread_t consumserThread; pthread_create(&consumserThread, NULL, consumer, NULL); for (int i = 0; i < 10; i++) { pthread_mutex_lock(&lock); node *tmp = malloc(sizeof(node)); tmp->data = i; tmp->next = head; printf("produce data:%d\n", tmp->data); head = tmp; pthread_cond_signal(&cond); pthread_mutex_unlock(&lock); sleep(1); } pthread_join(consumserThread, NULL); return 0; }
Please call me JiangYouDang!