哲学家问题之死锁:A Difficult Philosopher Problem

通过使用Semaphore和线程来模拟哲学家就餐问题,解决死锁并确保至少四位哲学家可以拿起筷子吃饭。每个哲学家随机思考一段时间后尝试拿起筷子吃饭。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Threading;

public class philosopher_dining
{
    private static Semaphore[] self = new Semaphore[5];  //number of chopsticks per pholosophor
    private static Semaphore preventStavation = new Semaphore(0, 4);//allow 4 persons pickup
    private static int seed = 12;//time

    private enum status
    {
        thinking, hungry, eating,
    }
    private static status[] states;

    private static void pickup(int i)
    {
        preventStavation.WaitOne();// wait to eat
        states[i] = status.hungry;
        Console.WriteLine("philosopher {0} is hungry and wants to eat.", i);
        test(i);// look for two resources
        if (states[i] != status.eating)
            self[i].WaitOne();  //the waiting personn
        else preventStavation.Release();  //if there are enough resources

        Console.WriteLine("philosopher {0} picked up chopsticks and began to eat.", i);
        Random fixRand = new Random(seed);
        seed++;
        int r = fixRand.Next() % 3000;
        Thread.Sleep(r);

        Console.Write("After {0} time,", r);
        Console.WriteLine("philosopher {0} put down chopsticks  and beggin thinking.", i);
        putdown(i);
        preventStavation.Release();
    }

    private static void putdown(int i)
    {
        states[i] = status.thinking;
        test((i + 4) % 5);
        test((i + 1) % 5);
    }


    private static void test(int i)// look for two resources and change states
    {

        if (states[(i + 4) % 5] != status.eating &&
            states[(i + 1) % 5] != status.eating &&
            states[i] == status.hungry)
        {
            states[i] = status.eating;
            self[i].Release();
        }

    }

    public static void Main()
    {

        for (int i = 0; i < 5; i++)
            self[i] = new Semaphore(0, 1);

        preventStavation.Release();

        states = new status[5];

        for (int i = 0; i < 5; i++)
            states[i] = status.thinking;

        for (int i = 0; i < 5; i++)
        {
            Thread t = new Thread(new ParameterizedThreadStart(Dining));
            t.Start(i);
        }
        Thread.Sleep(500);//block semapphore
        Console.ReadKey();
    }

    private static void Dining(object i)
    {
        Random fixRand = new Random(seed);
        seed++;
        int r = fixRand.Next() % 1000;
        Thread.Sleep(r);
        pickup((int)i);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值