一 回顾
1 因为临界资源空的原因 在上一节引出了一个条件变量 (不是一把锁)
2 又通过条件变量 引出了生产者和消费者的模型 并且消费者是主导地位 他不会生产节点 只会消耗
3 消费者 在等待阻塞实际上是 帮了 生产者解锁 让生产者工作
完了之后就会释放资源 最后就会告诉消费者 可以吃饼了
4 消费者为了 保护临界资源 会先进行加锁 最后才是解锁 这样的饼就吃的安心了
二 信号量函数



 
因为信号量就是一把锁 直接画图 演示

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
}Node;
Node *head=NULL;
sem_t sem1;
sem_t sem2;
void *durporcer(void *arg)
{
while(1)
{
Node *news=(Node *)malloc(sizeof(Node));
news->data=rand()%1000;
sem_wait(&sem1);
news->next=head;
head=news;
printf("durporcer is ===%d\n",news->data);
sem_post(&sem2);
sleep(rand()%3);
}
}
void *customer(void *arg)
{
while(1)
{
sem_wait(&sem2);
Node *semm=head;
head=head->next;
printf("customer is ===%d\n",head->data);
sem_post(&sem1);
sleep(rand()%3);
}
}
void main()
{
pthread_t p1,p2;
sem_init(&sem1,0,4);
sem_init(&sem2,0,0);
pthread_create(&p1,NULL,durporcer,NULL);
pthread_create(&p2,NULL,customer,NULL);
pthread_join(p1,NULL);
pthread_join(p2,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
}

|