_紫萱

操作系统第6次实验报告:使用信号量解决进程互斥访问

  • 姓名:黄财泽
  • 学号:201821121014
  • 班级:计算1811

 

一、实验目的

通过编程进一步了解信号量。

二、实验内容

在服务器上用Vim编写一个程序:使用信号量解决任一个经典PV问题,测试给出结果,并对解释运行结果。

三、实验报告

1. 选择哪一个问题

选择哲学家进餐的问题

2. 给出伪代码

semaphore chopstick[5]={1,1,1,1,1};
semaphore count=4; // 设置一个count,最多有四个哲学家可以进来
void philosopher(int i)
{
    while(true)
    {
        think();
        wait(count); //请求进入房间进餐 当count为0时 不能允许哲学家再进来了
        wait(chopstick[i]); //请求左手边的筷子
        wait(chopstick[(i+1)%5]); //请求右手边的筷子
        eat();
        signal(chopstick[i]); //释放左手边的筷子
        signal(chopstick[(i+1)%5]); //释放右手边的筷子
        signal(count); //离开饭桌释放信号量
    }
}

 

3. 给出完整代码

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <pthread.h>
#include <errno.h>
#include <math.h>
//筷子作为mutex
pthread_mutex_t chopstick[6] ;
void *eat_think(void *arg)
{
    char phi = *(char *)arg;
    int left,right; //左右筷子的编号
    switch (phi){
        case 'A':
            left = 5;
            right = 1;
            break;
        case 'B':
            left = 1;
            right = 2;
            break;
        case 'C':
            left = 2;
            right = 3;
            break;
        case 'D':
            left = 3;
            right = 4;
            break;
        case 'E':
            left = 4;
            right = 5;
            break;
    }
 
    int i;
    for(;;){
        usleep(3); //思考
        pthread_mutex_lock(&chopstick[left]); //拿起左手的筷子
        printf("Philosopher %c fetches chopstick %d\n", phi, left);
        if (pthread_mutex_trylock(&chopstick[right]) == EBUSY){ //拿起右手的筷子    
            pthread_mutex_unlock(&chopstick[left]); //如果右边筷子被拿走放下左手的筷子
            continue;
        }
        
    //    pthread_mutex_lock(&chopstick[right]); //拿起右手的筷子,如果想观察死锁,把上一句if注释掉,再把这一句的注释去掉
        printf("Philosopher %c fetches chopstick %d\n", phi, right);
        printf("Philosopher %c is eating.\n",phi);
        usleep(3); //吃饭
        pthread_mutex_unlock(&chopstick[left]); //放下左手的筷子
        printf("Philosopher %c release chopstick %d\n", phi, left);
        pthread_mutex_unlock(&chopstick[right]); //放下左手的筷子
        printf("Philosopher %c release chopstick %d\n", phi, right);
 
    }
}
int main(){
    pthread_t A,B,C,D,E; //5个哲学家
 
    int i;
    for (i = 0; i < 5; i++)
        pthread_mutex_init(&chopstick[i],NULL);
    pthread_create(&A,NULL, eat_think, "A");
    pthread_create(&B,NULL, eat_think, "B");
    pthread_create(&C,NULL, eat_think, "C");
    pthread_create(&D,NULL, eat_think, "D");
    pthread_create(&E,NULL, eat_think, "E");
 
    pthread_join(A,NULL);
    pthread_join(B,NULL);
    pthread_join(C,NULL);
    pthread_join(D,NULL);
    pthread_join(E,NULL);
    return 0;
}

 

4. 运行结果并解释

哲学家a拿起筷子5

 

 哲学家e拿起筷子4

哲学家c拿起筷子c

 

posted on 2020-05-30 13:38  _紫萱  阅读(292)  评论(0编辑  收藏  举报

导航