【问题标题】:C# Threading: Using Monitor.Wait, Lock and PulseAllC# 线程:使用 Monitor.Wait、Lock 和 PulseAll
【发布时间】:2009-10-14 20:15:38
【问题描述】:

我是 CSharp 和线程的新手。

为了熟悉 Monitor.Wait、Monitor.lock 和 Monitor.PulseAll,我构建了一个如下所述的场景。

“足球场由不同的球队共享用于练习目的。任何时候只有一支球队可以使用场地进行练习。一支球队可以使用场地进行 30 分钟的练习。一旦时间达到 25 分钟,它应该向其他球队发出信号线程将在 5 分钟后释放地面。当地面潮湿时(枚举有三个值 free、allotted、wet),不允许任何团队锁定地面,所有人都应该等待 10 分钟”

老实说,我不知道如何将描述转化为实际编码。根据我的理解,我设计了大纲。

namespace ThreadingSimulation
 {

  // A Random Activity can be picked up from this enum by a team

         public enum RandomGroundStatus
         {
             free,
             allotted,
             Wet          
         }

class FootBallGround
{

    public void Playing(object obj)
    {
      // Here the name of the team which is using the  ground will be printed
      // Once the time is reached to 25 minnutes the active thread acquired
      // the lock will signal  other threads    

    }

   public void GroundCleaningInProgress(object obj)
   {

      // Ground cleaning is in progress all of you
      // wait for 10 minutes

   }

}    




 class Team
   {
     string teamName;  

      static void Main()
      {

        //select random value for GrandStatus from enum

       // if the ground is wet no team is allowed to get the
       // ground for 10 minutes  

        //if the ground is free "Team A" locks the ground

        // otherwise "Team B" locks the ground

      }

   }

}

这里我不知道如何申请锁和信号。请帮助我。

【问题讨论】:

标签: c# multithreading


【解决方案1】:

实际上,您的场景并没有大量映射到 lock - 但我们还是会尝试;-p

我稍微调整了设置;而是:

  • 一个实体一次可以拥有理由
  • 当团队完成时,他们会告诉他们看到的第一个人(如果有人在等待)
  • 当清洁工结束时,他们很吵 - 所以每个人都会注意到他们离开并试图上场

这是代码;请注意,他们在使用场地时没有锁,因为这会阻止其他人加入Pulse 的队列。

实际上,我们可以使用 just lock(根本不使用 Pulse)来完成所有这些操作,并且只使用标准的阻塞行为。但此示例显示 PulsePulseAll 在满足条件时用于重新激活线程。

using System;
using System.Threading;
interface IGroundUser
{
    bool Invoke(); // do your stuff; return true to wake up *everyone*
                   // afterwards, else false
}
class Team : IGroundUser
{
    private readonly string name;
    public Team(string name) { this.name = name; }
    public override string ToString() { return name; }
    public bool Invoke()
    {
        Console.WriteLine(name + ": playing...");
        Thread.Sleep(25 * 250);
        Console.WriteLine(name + ": leaving...");
        return false;
    }
}
class Cleaner : IGroundUser
{
    public override string ToString() {return "cleaner";}
    public bool Invoke()
    {
        Console.WriteLine("cleaning in progress");
        Thread.Sleep(10 * 250);
        Console.WriteLine("cleaning complete");
        return true;
    }
}
class FootBallGround
{
    static void Main()
    {
        var ground = new FootBallGround();
        ThreadPool.QueueUserWorkItem(delegate { ground.UseGrounds(new Team("Team A")); });
        ThreadPool.QueueUserWorkItem(delegate { ground.UseGrounds(new Team("Team B")); });
        ThreadPool.QueueUserWorkItem(delegate { ground.UseGrounds(new Cleaner()); });
        ThreadPool.QueueUserWorkItem(delegate { ground.UseGrounds(new Team("Team C")); });
        ThreadPool.QueueUserWorkItem(delegate { ground.UseGrounds(new Team("Team D")); });
        ThreadPool.QueueUserWorkItem(delegate { ground.UseGrounds(new Team("Team E")); });
        Console.ReadLine();

    }
    bool busy;
    private readonly object syncLock = new object();
    public void UseGrounds(IGroundUser newUser)
    {
        // validate outside of lock
        if (newUser == null) throw new ArgumentNullException("newUser");
        // only need the lock when **changing** state
        lock (syncLock)
        {
            while (busy)
            {
                Console.WriteLine(newUser + ": grounds are busy; waiting...");
                Monitor.Wait(syncLock);
                Console.WriteLine(newUser + ": got nudged");
            }
            busy = true; // we've got it!
        }
        // do this outside the lock, allowing other users to queue
        // waiting for it to be free
        bool wakeAll = newUser.Invoke();

        // exit the game
        lock (syncLock)
        {
            busy = false;
            // wake up somebody (or everyone with PulseAll)
            if (wakeAll) Monitor.PulseAll(syncLock);
            else Monitor.Pulse(syncLock);
        }
    }    
}    

【讨论】:

  • 不错,无可挑剔和巧妙的答案。 :)
【解决方案2】:

对于锁定和多线程应用程序要始终记住的重要一点是,锁定只有在所有您访问锁定资源的代码遵循相同的规则时才有效,即如果一个线程可以锁定资源,可以访问同一资源的所有其他线程都应在访问该资源之前使用锁。

监控和锁定

lock 关键字是Monitor 类的便捷包装器。这意味着lock(obj)Monitor.Enter(obj) 相同(尽管Monitor 具有附加功能,如果它无法获得对象的锁定,则在一段时间后超时)。

脉冲事件和线程

当多个线程正在等待获取某个资源的锁定时,您可以通过代码在所有者线程完成该资源时发出信号。这称为signallingpulsing,可以通过Monitor.PulseMonitor.PulseAllManualResetEvent.Set 甚至AutoResetEvent.Set 完成。

足球示例

因此,下面的足球示例将被编码为包含线程锁定,如下所示:

 namespace ThreadingSimulation
 {

   // A Random Activity can be picked up from this enum by a team

    public enum RandomGroundStatus
    {
        Free,
        Allotted,
        Wet          
    }

 class FootBallGround
 {
     private Team _currentTeam;

     // Set the initial state to true so that the first thread that 
     // tries to get the lock will succeed
     private ManualResetEvent _groundsLock = new ManualResetEvent(true);

     public bool Playing(Team obj)
     {
       // Here the name of the team which is using the  ground will be printed
       // Once the time is reached to 25 minutes the active thread the lock will
       // signal other threads    
       if (!_groundsLock.WaitOne(10))
         return false;

       _currentTeam = obj;

       // Reset the event handle so that no other thread can come into this method
       _groundsLock.Reset();    

       // Now we start a separate thread to "timeout" this team's lock 
       // on the football grounds after 25 minutes
       ThreadPool.QueueUserWorkItem(WaitForTimeout(25));                  
     }

    public void GroundCleaningInProgress(object obj)
    {

       // Ground cleaning is in progress all of you wait for 10 minutes

    }

    private void WaitForTimeout(object state)
    {
         int timeout = (int)state;

         // convert the number we specified into a value equivalent in minutes
         int milliseconds = timeout * 1000;
         int minutes = milliseconds * 60;

         // wait for the timeout specified 
         Thread.Sleep(minutes);

         // now we can set the lock so another team can play
         _groundsLock.Set();
     }
 }    

 class Team
  {
      string teamName;  
      FootBallGround _ground;

       public Team(string teamName, FootBallGround ground)
       {
          this.teamName = teamName;
          this._ground = ground;      
       }

       public bool PlayGame()
       {
            // this method returns true if the team has acquired the lock to the grounds
            // otherwise it returns false and allows other teams to access the grounds
            if (!_ground.Playing(this))
               return false;
            else
               return true;
       }
  }


  static void Main()
  {
         Team teamA = new Team();
         Team teamB = new Team();

         // select random value for GrandStatus from enum
         RandomGroundStatus status = <Generate_Random_Status>;

         // if the ground is wet no team is allowed to get the
         // ground for 10 minutes.
         if (status == RandomGroundStatus.Wet)
            ThreadPool.QueueUserWorkItem(WaitForDryGround);
         else
         {
             // if the ground is free, "Team A" locks the ground
             // otherwise "Team B" locks the ground

             if (status == RandomGroundStatus.Free)
             {
               if (!teamA.PlayGame())
                  teamB.PlayGame();
             }
          }
    }

}

** 备注 **

  • 使用ManualResetEvent 而不是lockMonitor,因为我们希望直接控制锁的状态被脉冲以使其他线程能够玩足球游戏.

  • FootBallGrounds 的引用传递给每个Team,因为每支球队都将在特定的足球场上比赛,并且每个足球场都可能被另一支球队占据

  • FootBallGround 上传递对当前球队的引用,因为一次只能有一支球队在场地上比赛。

  • 使用ThreadPool.QueueUserWorkItem,因为它创建简单线程比我们手动创建线程更有效。理想情况下,我们也可以使用 Timer 实例。

【讨论】:

  • 感谢 Mike 花费您宝贵的时间 :)
猜你喜欢
  • 1970-01-01
  • 2011-07-29
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 2014-06-25
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多