最近六级考完,没啥事。刚好有门操作系统课程设计,于是就打开了阔别已久的虚拟机。。。。
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
int number=0; //馆内的人数;
int buffer[5]={-1,-1,-1,-1,-1}; //-1代表空座位
sem_t sem; //信号量
pthread_mutex_t mutex;
void *thr_fn(void * pth_id)
{
int chair_id, reader_id;
int time;
reader_id = *(int *)pth_id ;
sleep(1);
pthread_mutex_lock(&mutex);
printf("No.%d Reader Entered!\n", reader_id);
number++;
printf("%d people in the reading room...\n",number);
pthread_mutex_unlock(&mutex);
sem_wait(&sem);
for(chair_id = 0;chair_id < 5 ;chair_id++){
if(buffer[chair_id] == -1){
buffer[chair_id] = reader_id;
break;
}
}
printf("No.%d Reader sit at No.%d Seat\n",reader_id,chair_id + 1);
time = rand() % 50;
sleep(time + 3);
printf("No.%d Reader has been finished reading, Exit!\n",reader_id );
buffer[chair_id] = -1;
sem_post(&sem);
pthread_mutex_lock(&mutex);
number--;
pthread_mutex_unlock(&mutex);
pthread_exit;
}
int main(void){
int err,t_id,j;
void *pth_id;
pth_id = &t_id;
pthread_t t[10];
pthread_mutex_init(&mutex,NULL);
sem_init(&sem,0,5);
for(t_id = 0; t_id < 10;t_id++){
err=pthread_create(&t[t_id],NULL,thr_fn,pth_id);
if(err != 0)
printf("ERROR! CREATE THREAD FAILED!!!\n");
else
printf("No.%d THREAD READY.\n",t_id);
}
for(i = 0, i<10, i++)
pthread_join(t[i],NULL);
return 0;
}
这段多线程的实现的是阅览室占座问题。打印结果时似乎有点小问题,能交差就好。。。