#实现语言: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();
}
}
}