C#互斥體——Mutex

來源:互聯網
上載者:User

標籤:

Mutex對象是一個同步基元,可以用來做線程間的同步。

若多個線程需要共用一個資源,可以在這些線程中使用Mutex同步基元。當某一個線程佔用Mutex對象時,其他也需要佔用Mutex的線程將處於掛起狀態。

範例程式碼:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace myTest{    class Program    {        static List<string> enterList = new List<string>();//用來記錄結果        static Mutex mt = new Mutex();//建立一個同步基元        static int threadNum = 3, round = 3; //開啟3個線程,每個線程測試3輪        //階段控制對象,每一輪完成後列印結果        static Barrier br = new Barrier(threadNum, (b) =>           {               Console.WriteLine(String.Format("第{0}輪測試完成,線程擷取互斥體情況如下:",(b.CurrentPhaseNumber+1)));               foreach (string enter in enterList)               {                   Console.WriteLine(enter);               }               enterList.Clear();               if (b.CurrentPhaseNumber == round-1)               {                   Console.WriteLine("所有測試完成!");                   Console.ReadLine();               }           });                 static void Main(string[] args)        {           int i;           Thread t;           for (i = 0; i < threadNum; i++)           {               t = new Thread(startTest);               t.Name = "t" + (i+1);               t.Start();           }        }        static void startTest(){            int i;             for (i = 0; i < round; i++)            {                testMutex();            }        }        static void testMutex()        {            mt.WaitOne();            enterList.Add(String.Format("{0}-線程{1}擷取互斥體", DateTime.Now.ToString(), Thread.CurrentThread.Name));            Thread.Sleep(1000);            enterList.Add(String.Format("{0}-線程{1}釋放互斥體", DateTime.Now.ToString(), Thread.CurrentThread.Name));            mt.ReleaseMutex();            br.SignalAndWait();        }            }}

C#互斥體——Mutex

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.