阅览室问题(C#实现)

#实现语言:C#
#问题描述
有一个阅览室,共有10个座位,读者进入时必须先在一张登记表上登记,该表为每一座位列一表目,包括座号和读者姓名等,读者离开时要消掉登记的信息
#问题分析
读者的动作有两个,一是填表进入阅览室,这时要考虑阅览室里是否有座位;一是读者阅读完毕,离开阅览室,这时的操作要考虑阅览室里是否有读者.读者在阅览室读书时,由于没有引起资源的变动,不算动作变化.
算法的信号量有三个:SeatCount——表示阅览室是否有空座位(初值为10,代表阅览室的空座位数);用于互斥的Mutex,初值为1.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        private static Semaphore SeatCount, Mutex;
        private static string[] table = new string[10];  //模拟座位登记表
        static void Main(string[] args)
        {
            SeatCount = new Semaphore(10, 10);
            Mutex = new Semaphore(1, 1);
            for (int i = 0; i < 100; i++) // i代表读者数
            {
                Thread aa = new Thread(reader);
                aa.Start();
            }
        }
        public static void reader()
        {
            SeatCount.WaitOne();
            Mutex.WaitOne();
            for (int i = 0; i < 10; i++)
            {
                if (table[i] == null || table[i] == "")
                {
                    Console.WriteLine("已登记");
                    table[i] = "AAA";
                    break;
                }
            }
            Mutex.Release();
            Console.WriteLine("阅读中");
            Thread.Sleep(5000);
            Mutex.WaitOne();
            Console.WriteLine("注销");
            for (int i = 0; i < 10; i++)
            {
                if (table[i] == "AAA")
                {
                    table[i] = "";
                    break;
                }
            }
            Mutex.Release();
            SeatCount.Release();


        }
    }
}
  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值