//
// 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;
}

  

相关文章:

  • 2021-05-17
  • 2021-11-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-09
  • 2021-05-09
  • 2021-11-30
猜你喜欢
  • 2021-09-29
  • 2022-12-23
  • 2021-08-25
  • 2021-07-13
  • 2021-11-12
  • 2021-05-24
  • 2021-05-23
相关资源
相似解决方案