#include #include #include #include struct dumbQueue *msgQueue; struct dumbQueue* dumbQueue_create (void); void dumbQueue_push (struct dumbQueue *q, void *element); void* dumbQueue_pop (struct dumbQueue *q); int dumbQueue_isEmpty(struct dumbQueue *q); pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cv = PTHREAD_COND_INITIALIZER; _Thread_local char *msg; void producer(void) { while (1) { msg = malloc(255); scanf("%*[\n]"); scanf("%254[^\n]", msg); { pthread_mutex_lock(&mtx); dumbQueue_push(msgQueue, msg); pthread_cond_signal(&cv); pthread_mutex_unlock(&mtx); } } } void *consumer(void *_) { while (1) { { pthread_mutex_lock(&mtx); while (dumbQueue_isEmpty(msgQueue)) pthread_cond_wait(&cv, &mtx); msg = dumbQueue_pop(msgQueue); pthread_mutex_unlock(&mtx); } printf("%s\n", msg); free(msg); } } int main(void) { msgQueue = dumbQueue_create(); pthread_t tid; pthread_create(&tid, NULL, consumer, NULL); producer(); } /*****/ struct dumbQueue { /* T */ struct dumbQueue_e { /* h */ void *element; /* i */ struct dumbQueue_e *next; /* s */ } *head, *tail; /* */ }; /* i */ /* s */ struct dumbQueue *dumbQueue_create(void) { /* */ struct dumbQueue *q = malloc(sizeof(struct dumbQueue)); /* j */ q->head = malloc(sizeof(struct dumbQueue_e)); /* u */ q->head->next = NULL; /* s */ q->tail = q->head; /* t */ return q; /* */ } /* a */ /* */ void dumbQueue_push(struct dumbQueue *q, void *element) { /* d */ q->tail->next = malloc(sizeof(struct dumbQueue_e)); /* u */ q->tail = q->tail->next; /* m */ q->tail->next = NULL; /* b */ q->tail->element = element; /* */ } /* q */ /* u */ void *dumbQueue_pop(struct dumbQueue *q) { /* e */ struct dumbQueue_e *next = q->head->next; /* u */ free(q->head); /* e */ q->head = next; /* */ return q->head->element; /* i */ } /* m */ /* p */ int dumbQueue_isEmpty(struct dumbQueue *q) { /* l */ return q->head->next == NULL; /*****/ }