線程同步之竟態條件

來源:互聯網
上載者:User

 如果兩個或多個線程訪問相同的對象,或者訪問不同步的共用狀態,就會出現竟態條件。

 在單核的CPU中,若線程調度是搶先式的,就會出現此問題;在多CPU或雙核CPU系統中,其多個線程可以同時運行,竟態條件這個問題會比單核CPU系統中較多。

  Example:

   public class StateObject{

   int state=5;

    //避免竟態條件的第二種方法是將共用對象設為安全執行緒的對象。

  Object sync= new Object();

            public void ChangeState(int loop)

  {

    lock(sync)

     {

     if(state==5)

        {

                   state++;

     

            Trace.Assert(state==6,"Race Condition occurred after"+loop+" loops");

           

            }

          state=5;

  }

}

 

}

 

    public class SampleThread

     {

        public void RaceCondtion(object o)

          {

             StateObject so= o as StateObject;

             int i=0;

             while(true)

             {

                 lock(so)//鎖定共用對象,可以避免竟態條件發生

                    {

                         so.ChangeState(i++);

                    }

             }

          }

     }

  public static class MainCllass

   {

      static void Main()

     {

        StateObject o =  new StateObject();

       for(int i=0;i<20;i++)

        {

            new thread(new SampleThread().RaceCondtion)).start(o);

        }

     }

   }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.