C#线程:使用Monitor.Wait,Lock和PulseAll

use*_*973 15 c# multithreading

我是CSharp和Threading的新手.

为了熟悉Monitor.Wait,Monitor.lock和Monitor.PulseAll,我构建了一个下面描述的场景.

"不同的球队正在为实践目的分享一个FootballGround.任何时候只有一个团队可以使用他们的练习场.一个团队可以使用地面练习30分钟.一旦时间达到25分钟,它应该发出信号5分钟后地面即将释放的线程.当地面潮湿时(enum有三个值自由,分配,潮湿)没有任何队员可以锁定地面,所有人都应该等待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

      }

   }

}
Run Code Online (Sandbox Code Playgroud)

在这里,我不知道如何应用锁和signalls.kindly帮助我.

Mar*_*ell 13

实际上,你的场景并没有很大地映射到lock- 但我们无论如何都会尝试;-p

我稍微调整了一下设置; 代替:

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

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

在现实中,我们可以做所有的这与只是 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);
        }
    }    
}    
Run Code Online (Sandbox Code Playgroud)


Mik*_*e J 5

使用锁定和mutithreaded应用程序始终记住的重要一点是,只有在访问锁定资源的所有代码按相同规则播放时,锁定才有效,即如果一个线程可以锁定资源,则所有其他可以访问同一资源的线程应该在访问该资源之前使用锁.

监控和锁定

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

脉冲事件和线程

当许多线程等待获取某些资源的锁定时,通过代码,您可以在所有者线程完成资源时发出信号.这被称为信令脉冲,并且可以通过来完成Monitor.Pulse,Monitor.PulseAll,ManualResetEvent.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();
             }
          }
    }
Run Code Online (Sandbox Code Playgroud)

}

**笔记**

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

  • 传递到一个参考FootBallGrounds给每个Team因为各队具体的脚下球的理由和各足球场将发挥可以用另一支球队被占用

  • 传递给当前参加比赛的球队,FootBallGround因为一次只能有一支球队在球场上比赛.

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