多線程處理
- 問題描述
- 問題分析
- 代碼實作
問題描述
有一閱覽室,讀者進入時必須先在一張登記表上登記,該表為每一座位列一表目,包括座号、姓名。讀者離開時要登出登記資訊;
假如閱覽室共有100個座位,試用信号量和P、V操作來實作程序的同步算法。
問題分析
Semaphore(信号量)兩個:mutex(互斥),seatcount。
Thread(線程)N個:幾個讀者就有幾個線程。
代碼實作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace pv操作_圖書館問題_
{
class Program
{
private static Semaphore mutex, seatcount;
private static string[] table=new string[100];
static void Main(string[] args)
{
mutex = new Semaphore(1, 1);
seatcount = new Semaphore(100, 100);
Random r = new Random();
//假設有150讀者
for (int i = 1; i <= 150; i++)
{
Thread read = new Thread(reader);
read.Start(r.Next(1, 151));
}
}
public static void reader(object num) //座位号從0号到99号
{
int seatnumber=-1;
while(true)
{
seatcount.WaitOne();
mutex.WaitOne();
for (int i = 0; i < 100; i++)
{
if (table[i]==null||table[i]=="")
{
table[i] = num.ToString() + "号讀者";
seatnumber = i;
break;
}
}
Console.WriteLine(num.ToString() + "号讀者已填寫登記表");
mutex.Release();
Console.WriteLine(num.ToString() + "号讀者正在"+seatnumber+"号座位閱讀");
Thread.Sleep(5000);
mutex.WaitOne();
for (int i = 0; i < 100; i++)
{
if (table[i] == num.ToString()+"号讀者")
{
table[i] = "";
seatnumber = -1;
break;
}
}
Console.WriteLine(num.ToString() + "号讀者登出");
mutex.Release();
seatcount.Release();
}
}
}
}