线程的同步和互斥题目
题目:
设计生产者与消费者模型,缓冲区是一个大小为10的环。每个生产者产生一个0-1000的随机整数,存放在环空位中,消费者从环中取数据,并输出。一个生产者或消费者对应一个线程。
要避免:
(1)两个生产者同时向环的同一个位置放数据
(2)两个消费者同时从环的同一个位置取数据
(3)一个生产者和一个消费者同时分别对环的同一个位置进行放数据和取数据。
这题主要考的是线程的同步和互斥,主要涉及的PV操作思想是这样的
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define N 10
sem_t avail,ready;
sem_t mutex;
int buf[N];
int inpos=0,outpos=0;//数据输出
void Thread_Pi();//生产者
void Thread_Ci();//消费者
void sbuf_insert(buf);//数据插入
int sbuf_remove(buf);//数据输出
int main(){
pthread_t tid1,tid2;
//信号量初始化
sem_init(&avail,0,N);//avail代表缓冲区个数
sem_init(&ready,0,0);//ready代表已经存有数据的缓冲区个数
sem_init(&mutex,0,1);//mutex代表对缓冲区的操作
//创建线程
pthread_create(&tid1,NULL,Thread_Pi,NULL);
pthread_create(&tid2,NULL,Thread_Ci,NULL);
//回收已终止线程的资源
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
//销毁信号量
sem_destroy(&mutex);
sem_destroy(&avail);
sem_destroy(&ready);
//结束进程
exit(EXIT_SUCCESS);
}
void Thread_Pi(){
int item;
while(1){
item=rand()%1000;//取随机数
sem_wait(&avail);//P操作,查看是否有空闲的缓冲区
sem_wait(&mutex);//获取缓冲区控制权
sbuf_insert(item,buf);//插入数据
sem_post(&mutex);//V操作
sem_post(&ready);//有数据的缓冲区+1
printf("生产者在%d位置放入了数据%d\n",inpos,item);
sleep(1);
}
}
void Thread_Ci(){
int item;
while(1){
sem_wait(&ready);//P操作^[OB
sem_wait(&mutex);
item=sbuf_remove(buf);//取出数据
sem_post(&mutex);//V操作
sem_post(&avail);
printf("消费者在%d位置取出了数据%d\n",outpos,item);
sleep(1);
}
}
//插入数据
void sbuf_insert(int item,int buf[]){
buf[inpos]=item;
inpos=(inpos+1);
inpos=(inpos)%N;
}
//取出数据顺便将那个位置的数字置为-1
int sbuf_remove(int buf[]){
int item;
item=buf[outpos];
outpos=(outpos+1)%10;
buf[outpos]=-1;
return item;
}
运行结果如下
这只是一个很简单的实现,我只是记录下来方便以后查看。