linux系统编程:线程同步

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <pthread.h>struct goods{int id;struct goods *next;};pthread_mutex_t m;pthread_cond_t has_product;struct goods *head;void *producer(void *argv){struct goods *p = NULL;while (1){pthread_mutex_lock(&m);p = malloc(sizeof(struct goods));p->id = rand() % 100;p->next = head;head = p;printf("produce %d\n", p->id);pthread_mutex_unlock(&m);pthread_cond_signal(&has_product);//printf("produce %d\n", p->id);sleep(rand() % 2);}return (void *)0;}void *comsumer(void *argv){struct goods *p = NULL;while (1){pthread_mutex_lock(&m);//思考:pthread_cond_wait()的作用?while (NULL == head)pthread_cond_wait(&has_product, &m);p = head;head = head->next;printf("comsume %d\n", p->id);pthread_mutex_unlock(&m);//printf("comsume %d\n", p->id);free(p);sleep(rand() % 2);}return (void *)0;}int main(void){int i;//初始化条件变量和互斥量pthread_mutex_init(&m, NULL);pthread_cond_init(&has_product, NULL);head = NULL;pthread_t pro[2], com[3];for (i = 0; i < 2; i++)pthread_create(&pro[i], NULL, producer, NULL);for (i = 0; i < 3; i++)pthread_create(&com[i], NULL, comsumer, NULL);for (i = 0; i < 2; i++)pthread_join(pro[i], NULL);for (i = 0; i < 3; i++)pthread_join(com[i], NULL);//销毁条件变量和互斥量pthread_mutex_destroy(&m);pthread_cond_destroy(&has_product);return 0;}在代码中,我们开启两个线程作为生产者,三个线程作为消费者。产品使用链表存储,并且每次生产和消费都在链表头部发生。

,走过的路成为背后的风景,不能回头不能停留,若此刻停留,

linux系统编程:线程同步

相关文章:

你感兴趣的文章:

标签云: