C#读者写者问题:互斥失败了!
ejiue 2004-05-11 11:43:07 在C#里使用Mutex解决读者写者问题,运行时某个读者线程在调用ReleaseMutex()方法导致了如下异常:
“未处理的“System.ApplicationException”类型的异常出现在 mscorlib.dll 中。”
查看MSDN,原因为“调用线程不拥有互斥体”。
奇怪了,我并没有进行释放两次的操作。
另外,控制台输出显示:当有读者正在读的时候,写者竟然开始写了。
我调试时,发现最后一个读线程还没有解锁,写线程就开始输出了。
代码如下(读者优先):
private static Mutex rc = new Mutex();
private static Mutex wsem = new Mutex();
private static int readercount = 0;
private static void ReaderThreadProc_ReaderPriority()
{
string threadname = Thread.CurrentThread.Name;
int id = int.Parse(threadname);
int delay = Convert.ToInt32(GetThreadDelay(id)*1000);
int persist = Convert.ToInt32(GetThreadPersist(id)*1000);
Thread.Sleep(delay);
Console.WriteLine("{0} is requesting for reading",threadname);
rc.WaitOne();
readercount++;
if ( readercount == 1 )
{
wsem.WaitOne();
}
rc.ReleaseMutex();
Console.WriteLine("{0} is beginning reading",threadname);
Thread.Sleep(persist);
Console.WriteLine("{0} is ending reading",threadname);
try
{
rc.WaitOne();
readercount--;
if ( readercount == 0 )
{
wsem.ReleaseMutex();//调试发现这一行还没有解锁,写者竟然输出
}
rc.ReleaseMutex();//这一行在某个时刻会导致异常。
}
catch
{
;
}
}
private static void WriterThreadProc_ReaderPriority()
{
string threadname = Thread.CurrentThread.Name;
int id = int.Parse(threadname);
int delay = Convert.ToInt32(GetThreadDelay(id)*1000);
int persist = Convert.ToInt32(GetThreadPersist(id)*1000);
Thread.Sleep(delay);
Console.WriteLine("{0} is requesting for writing",threadname);
wsem.WaitOne();
//调试发现,某个时刻最后一个读者还未RleaseMutex,
//这里竟然先执行Console.WriteLine了。
//然后读者才执行RleaseMutex
Console.WriteLine("{0} is beginning writing",threadname);
Thread.Sleep(persist);
Console.WriteLine("{0} is ending writing",threadname);
wsem.ReleaseMutex();
}
郁闷。请朋友们帮我看看问题出在哪里?