这周帮老师做了一个介绍管程的PPT,很多书在讲操作系统中线程的管程时,都有标注上说,管程比较偏学术,没有哪个语言支持,像我的老师就问了很多同事,大家都不知道其实.NET平台已经实现了管程类来帮助我们管理线程。以下我用C#语言作为例子,来简单介绍一下。如果有哪位高手更加了解这个类,希望您可以多讲解一下,如果发现错误请提出!!非常感激~
注[3]:在C# 2.0中,Monitor.Enter()和Monitor.Exit()调用间要try/finally来保护,否则可能会导致一个Monitor.Exit()永远不会被调用的异常。
using System.Threading;
{
class UsingMonitor
{
private int sum = 0;
private int output = 0;
{
Thread Doperation = new Thread(new ThreadStart(DataHandle));
Thread Dprint = new Thread(new ThreadStart(Dataprint));
Dprint.Name = "print thread";
Doperation.Start();
Doperation.Join();
Dprint.Join();
}
{
Monitor.Enter(this);
for (int i = 0; i < 20; i++)
{
if (output == 10)
{
Monitor.Wait(this);//handle thread释放资源,进入等待列队
}
output++;
Console.WriteLine(Thread.CurrentThread.Name + " is handling the" + output + " data.");
Thread.Sleep(1000);
if (output == 10)
{
Monitor.Pulse(this);//handle thread 中的资源被释放,叫醒等待列队中的第一个线程。
Console.WriteLine();
}
}
void Dataprint()
{
Monitor.Enter(this);
do
{
if (output == 0)
{
Monitor.Wait(this);//print thread释放资源,进入等待列队
}
Console.WriteLine(Thread.CurrentThread.Name + " is printint the" + output + " data.");
Thread.Sleep(1000);
output--;
sum++;
Console.WriteLine("/t the totle of data:" + sum);
if (output == 0)
{
Monitor.Pulse(this););//print thread 中的资源被释放,叫醒等待列队中的第一个线程。
Console.WriteLine();
}
} while (sum < 20);
Monitor.Exit(this);
static void main()
{
UsingMonitor myUM = new UsingMonitor ();
myUM.StartThread();
Console .Write ("end");
Console .ReadLine();
}
}
}
执行结果:
Data handle thread is handling the 1 data.
…….
Data handle thread is handling the 10 data.
Data printe thread is printing the 10 data. The totle of data:1
…….
Data printe thread is printing the 1 data. The totle of data:10
…….
Data handle thread is handling the 1 data.
…….
Data handle thread is handling the 10 data.
Data printe thread is printing the 10 data. The totle of data:11
…….
Data printe thread is printing the 1 data. The totle of data:20
end
参考资料:
[1]《C# Programmer’s Reference》
清华大学出版社
[2]《Visual C# 范例精要解析》吕高旭 编著
清华大学出版社
[3] 《Essential C# 2.0》 Mark Michealis著
人们邮电出版社