同步基元Mutex
Mutex 互斥體 又稱同步基元 使用了System.Threading命名空間,本文將建立一個(gè)可以同步多任務(wù)行為的簡單示例。
新建一個(gè)控制臺(tái)應(yīng)用程序,新建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();
}
}
進(jìn)程Thread1和Thread2中,運(yùn)行到WaitOne()時(shí),需要申請拿到Mutex的所有權(quán)才可以繼續(xù)向下執(zhí)行,Thread1較Thread2先一步獲得Mutex的所有權(quán),所以Thread2必須等待Thread1釋放Mutex才可以繼續(xù)執(zhí)行。
控制臺(tái)Main函數(shù)添加測試代碼:
static void Main(string[] args){
ThreadMutex t = new ThreadMutex();
t.Test();
Console.ReadKey();
}
重新生成項(xiàng)目,F5運(yùn)行,結(jié)果如下:
值得注意的是,Mutex同步基元在整個(gè)操作系統(tǒng)中可見,即使不在調(diào)試期間,Mutex仍在其生命周期中,所以可能會(huì)出現(xiàn)運(yùn)行結(jié)果不同的狀況,這時(shí)只需耐心等待程序一次運(yùn)行完畢,Thread1和Thread2全部釋放Mutex后,再次調(diào)試程序即可。
轉(zhuǎn)載于:https://www.cnblogs.com/xwlyun/archive/2012/03/02/2377556.html
總結(jié)
- 上一篇: 2022 年国内智能手机出货量达 2.6
- 下一篇: 流水贷需要什么条件