操作系统实验中的读者写者问题
在Monitor.Exit(wmutex)处会引发异常:从不同步的代码块中调用了对象同步方法。
是什么原因啊?怎么改呢
public void Reader()
        {
            lock (rmutex)
            {
                if (ReadCount == 0)
                {
                    Monitor.Enter(wmutex);
                }
                ReadCount++;
            }
            listBox1.Items.Add(n.ToString()+"号读者开始读。" );
            int t=wr [n].Need *1000;
            Thread.Sleep(t);
            listBox1.Items.Add(n.ToString() + "号读者读写完毕。");
            lock (rmutex)
            {
                ReadCount--;
                if (ReadCount == 0)
                    Monitor.Exit(wmutex);
            }
        }
        public void Writer()
        {
            lock (wmutex)
            {
                listBox1.Items.Add(n.ToString ()+"号写者开始写。");
                int t = wr[n].Need * 1000;
                Thread.Sleep(t);
                listBox1.Items.Add(n.ToString() + "号写者读写完毕。");
            }
        }

解决方案 »

  1.   

    事实上,lock 关键字就是用 Monitor 类来实现的。例如:C#  复制代码 
    lock (x)
    {
        DoSomething();
    }
     这等效于:C#   
    System.Object obj = (System.Object)x;
    System.Threading.Monitor.Enter(obj);
    try
    {
        DoSomething();
    }
    finally
    {
        System.Threading.Monitor.Exit(obj);

      

  2.   

    加入这条语句试试
    CheckForIllegalCrossThreadCalls = false; //线程间可调用