close
C#在多個執行緒中,需要互相交握或是等待對方執行緒到達一個流程時回傳,就可以使用互斥鎖的方法去達到
例如:
執行緒一與執行緒二都需要存取Function X,但是X中有順序的問題時 EX:遞增或是計數
可能是需要等待執行緒一先進,就會先把執行權丟給執行緒一,然後等執行Function X後才把執行權放掉給別的執行緒執行
能夠掌握好這個做法,就能夠比較好的掌握平行執行緒的作法
範例碼:
private static Mutex mut = new Mutex();
private const int numIterations = 2;
private const int numThreads = 3;
int main()
{
Example ex = new Example();
ex.StartThreads();
}
class Example
{
public void StartThreads()
{
// 創建受保護資源的執行緒
for (int i = 0; i < numThreads; i++)
{
Thread newThread = new Thread(new ThreadStart(ThreadProc));
newThread.Name = String.Format("Thread{0}", i + 1);
newThread.Start();
}
{
public void StartThreads()
{
// 創建受保護資源的執行緒
for (int i = 0; i < numThreads; i++)
{
Thread newThread = new Thread(new ThreadStart(ThreadProc));
newThread.Name = String.Format("Thread{0}", i + 1);
newThread.Start();
}
// 主執行緒回傳至Main Function並且退出,但是應用程式繼續執行到所有前台執行緒都退出為止
}
private static void ThreadProc()
{
for (int i = 0; i < numIterations; i++)
{
UseResource();
}
}
{
for (int i = 0; i < numIterations; i++)
{
UseResource();
}
}
// 此為需要同步的方法,只能有一個執行緒能進入主要流程,其他的都在while裡面等,
// 要用while(true)的寫法,必須保證一定有離開Function的流程,不然很容易導致死結
private static void UseResource()
{
while (true)
{
{
while (true)
{
Console.WriteLine("{0} 正在請求 mutex", Thread.CurrentThread.Name);
// 如果有執行權就可以直接進入,如果沒有就等待WaitOne裡面的毫秒數,等待過後如果還是沒有執行權就回傳false
bool bRet = mut.WaitOne(1000);
if (bRet)
{
Console.WriteLine("{0} 進入保護區域", Thread.CurrentThread.Name);
bool bRet = mut.WaitOne(1000);
if (bRet)
{
Console.WriteLine("{0} 進入保護區域", Thread.CurrentThread.Name);
// 在這裡放需要同步的代碼,或是不可以同時執行的資源
// 模擬工作
Thread.Sleep(2000);
Thread.Sleep(2000);
Console.WriteLine("{0} 正在離開保護區域",Thread.CurrentThread.Name);
// 釋放Mutex
mut.ReleaseMutex();
Console.WriteLine("{0} 已釋放 mutex",Thread.CurrentThread.Name);
break;
}
else
{
Console.WriteLine("{0} 不會獲得 mutex",Thread.CurrentThread.Name);
Thread.Sleep(100);
}
}
}
~Example()
{
mut.Dispose();
}
}
mut.ReleaseMutex();
Console.WriteLine("{0} 已釋放 mutex",Thread.CurrentThread.Name);
break;
}
else
{
Console.WriteLine("{0} 不會獲得 mutex",Thread.CurrentThread.Name);
Thread.Sleep(100);
}
}
}
~Example()
{
mut.Dispose();
}
}
ㄓ
參考文獻:
https://docs.microsoft.com/zh-tw/dotnet/api/system.threading.mutex?view=netframework-4.7.2
文章標籤
全站熱搜
留言列表