日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

同步基元Mutex

發布時間:2023/12/19 52 豆豆
生活随笔 收集整理的這篇文章主要介紹了 同步基元Mutex 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Mutex 互斥體 又稱同步基元 使用了System.Threading命名空間,本文將建立一個可以同步多任務行為的簡單示例。


新建一個控制臺應用程序,新建ThreadMutex類,代碼如下:

class ThreadMutex
{
public void Test()
{
Thread t1 = new Thread(Thread1);
Thread t2 = new Thread(Thread2);
t1.Start();
t2.Start();
//t1.Start();
}

void Thread1()
{
Mutex m = new Mutex(false, "test");

//wait
Console.WriteLine("Thread1 wait the mutex");
bool b2 = m.WaitOne();

//get
Console.WriteLine("Thread1 get the mutex:" + b2);
Console.WriteLine("Thread1 do sth...");
Thread.Sleep(10000);

//release
Console.WriteLine("Thread1 release the mutex");
m.ReleaseMutex();
}

void Thread2()
{
Mutex m = new Mutex(false, "test");

//wait
Console.WriteLine("\t\t\t\t Thread2 wait the mutex");
bool b2 = m.WaitOne();

//get
Console.WriteLine("\t\t\t\t Thread2 get the mutex:" + b2);
Console.WriteLine("\t\t\t\t Thread2 do sth...");
Thread.Sleep(1000);

//release
Console.WriteLine("\t\t\t\t Thread2 release the mutex");
m.ReleaseMutex();
}
}

進程Thread1和Thread2中,運行到WaitOne()時,需要申請拿到Mutex的所有權才可以繼續向下執行,Thread1較Thread2先一步獲得Mutex的所有權,所以Thread2必須等待Thread1釋放Mutex才可以繼續執行。

控制臺Main函數添加測試代碼:

static void Main(string[] args)
{
ThreadMutex t = new ThreadMutex();
t.Test();

Console.ReadKey();
}

重新生成項目,F5運行,結果如下:

值得注意的是,Mutex同步基元在整個操作系統中可見,即使不在調試期間,Mutex仍在其生命周期中,所以可能會出現運行結果不同的狀況,這時只需耐心等待程序一次運行完畢,Thread1和Thread2全部釋放Mutex后,再次調試程序即可。

轉載于:https://www.cnblogs.com/xwlyun/archive/2012/03/02/2377556.html

總結

以上是生活随笔為你收集整理的同步基元Mutex的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。