最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#多線程中的互斥鎖Mutex

 更新時(shí)間:2022年04月20日 09:16:37   作者:農(nóng)碼一生  
這篇文章介紹了C#多線程中的互斥鎖Mutex,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

一、簡介

Mutex的突出特點(diǎn)是可以跨應(yīng)用程序域邊界對資源進(jìn)行獨(dú)占訪問,即可以用于同步不同進(jìn)程中的線程,這種功能當(dāng)然這是以犧牲更多的系統(tǒng)資源為代價(jià)的。

主要常用的兩個(gè)方法:

  • public virtual bool WaitOne() 阻止當(dāng)前線程,直到當(dāng)前 System.Threading.WaitHandle 收到信號(hào)獲取互斥鎖。
  • public void ReleaseMutex() 釋放 System.Threading.Mutex 一次。

二、代碼

案例一:

    class Program
    {
        private static Mutex mutex = new Mutex();
        static void Main(string[] args)
        {
            Thread[] thread = new Thread[3];
            for (int i = 0; i < 3; i++)
            {
                thread[i] = new Thread(ThreadMethod1);//方法引用
                thread[i].Name = "Thread-" + (i+1).ToString();
            }
            for (int i = 0; i < 3; i++)
            {
                thread[i].Start();
            }
            Console.ReadKey();
        }
        public static void ThreadMethod1(object val)
        {           
            mutex.WaitOne();    //獲取鎖
            for (int i = 1; i <=5; i++)
            {
                Console.WriteLine("{0}循環(huán)了{(lán)1}次", Thread.CurrentThread.Name, i);
            }
            mutex.ReleaseMutex();  //釋放鎖
        }
    }

運(yùn)行結(jié)果:

案例二:

    class Program
    {
        private static Mutex mutex = new Mutex();
        private static int sum = 0;
        static void Main(string[] args)
        {
            Task<int> task = new Task<int>(ThreadFunction);
            task.Start();
            Console.WriteLine($"{DateTime.Now} task started!");
            Thread.Sleep(2000);//Main主線程

            Console.WriteLine($"{DateTime.Now} Get siginal in Main!");
            mutex.WaitOne();
            Console.WriteLine($"{DateTime.Now} Get siginal in main!");

            Console.WriteLine($"{DateTime.Now} Result is {task.Result}");
            Console.ReadKey();
        }
        private static int ThreadFunction()
        {
            Console.WriteLine($"{DateTime.Now} Get siginal in ThreadFunction!");
            mutex.WaitOne();  //獲取鎖
            for (int i = 0; i <= 10; i++)
            {
                sum += i;
                Thread.Sleep(1000);
            }
            Console.WriteLine($"{DateTime.Now} Release mutex in ThreadFunction!");
            mutex.ReleaseMutex();  //釋放鎖

            return sum;
        }
    }

運(yùn)行結(jié)果:

三、總結(jié)

為避免發(fā)送多線程發(fā)生死鎖,Mutex的WaitOne()和ReleaseMutex()需成對配合使用。

到此這篇關(guān)于C#互斥鎖Mutex的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

门头沟区| 河源市| 富蕴县| 江安县| 容城县| 广东省| 白河县| 博野县| 朝阳县| 饶河县| 西昌市| 错那县| 延安市| 靖边县| 得荣县| 黎川县| 上虞市| 东海县| 莱州市| 白城市| 吐鲁番市| 太白县| 毕节市| 临武县| 咸宁市| 湘潭县| 和龙市| 论坛| 遵义市| 杨浦区| 延庆县| 永兴县| 巍山| 鹰潭市| 宁晋县| 石阡县| 浦东新区| 周至县| 溧水县| 楚雄市| 平湖市|