《现代操作系统》 第二章 进程和线程
多线程编程真的很麻烦。。。
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>
#define N 100//缓冲区大小
//三个信号量
sem_t mutex;//控制对临界区打访问
sem_t empty;//缓冲区的空槽数目
sem_t full;//缓冲区的满槽数目
int buffer[N];//缓冲区
int front=0;//缓冲区队列头
int rear=1;//缓冲区队列尾
void *producer (void * tid)
{
int item=0;//要存放的数字
while(item<=100)
{
item++;//产生缓冲区数据
sem_wait(&empty);//将空槽数目建一
sem_wait(&mutex);//进入临界区
buffer[rear]=item;//缓冲区中放入数据
rear=(rear+1)%N;//队尾+1
printf(" producer %d\n",item);
sem_post(&mutex);//离开临界区
sem_post(&full);//将满槽数目加一
}
}
void *consumer(void * tid)
{
while(true)
{
sem_wait(&full);
sem_wait(&mutex);
front=(front+1)%N;
printf("consumer %d\n",buffer[front]);
sem_post(&mutex);
sem_post(&empty);
}
}
int main()
{
sem_init(&mutex,0,1);//初始化信号量,赋值为1
sem_init(&empty,0,N);
sem_init(&full,0,0);
pthread_t pro,con;//线程号
pthread_create(&con,0,consumer,NULL);//创建线程
pthread_create(&pro,0,producer,NULL);
pthread_join(pro,0);//如果没有pthread_join;主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了
pthread_join(con,0);//加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行
//pthread_join函数会让主线程阻塞,直到所有线程都已经退出
sem_destroy(&full);//销毁
sem_destroy(&empty);
sem_destroy(&mutex);
}