系列1 曾經說過:每一個線程都有本身的資源,但代碼區是共享的,即每一個線程均可以執行相同的函數。express
這可能帶來的問題就是多個線程同時執行一個函數,並修改同一變量值,這將致使數據的混亂,產生不可預料的結果。看下面的示例:多線程
private void btnThread_Click(object sender, EventArgs e)
{
Thread t1 = new Thread(ChangeTextBox);
t1.Start();
Thread t2 = new Thread(ChangeTextBox);
t2.Start();
}
void ChangeTextBox()
{
for (int i = 0; i < 10000; i++)
{
int num = int.Parse(txtNum.Text);
num++;
txtNum.Text = num.ToString();
}
}
結果,計數非但不是20000,相差的還很遠。這是由於 CPU 在線程切換的過程當中,2 個線程屢次發生取出相同值進行運算。這顯然不是咱們想要達到的目的。app
要解決這一問題也很是簡單,只需爲這段代碼加上 Lock 鎖定:dom
private static object obj = new object();
void ChangeTextBox()
{
for (int i = 0; i < 10000; i++)
{
lock(obj)
{
int num = int.Parse(txtNum.Text);
num++;
txtNum.Text = num.ToString();
}
}
}
C# 提供了一個關鍵字 lock,它能夠把一段代碼定義爲互斥段(critical section),互斥段在一個時刻內只容許一個線程進入執行,而其餘線程必須等待。函數
在C#中,關鍵字 lock 的定義:lock(expression) statement_blockoop
expression 表明你但願跟蹤的對象,一般是對象引用。若是你想保護一個類的實例,你可使用 this;若是你想保護一個靜態變量(如互斥代碼段在一個靜態方法內部),通常使用類名就能夠了。而 statement_block 就是互斥段的代碼,這段代碼在一個時刻內只可能被一個線程執行。測試
再看一個 Lock 關鍵字的示例:this
internal class Account
{
int balance;
Random r = new Random();
internal Account(int initial)
{
balance = initial;
}
internal void Withdraw(int amount)
{
if (balance < 0)
{
throw new Exception("Negative Balance");
}
lock (this)
{
// 下面的代碼保證在當前線程修改 balance 的值完成以前
// 不會有其餘線程也執行這段代碼來修改 balance 的值
// 所以,balance 的值是不可能小於 0 的
Console.WriteLine("Current Thread:" + Thread.CurrentThread.Name
+ " balance:" + balance.ToString() + " amount:" + amount);
// 若是沒有 lock 關鍵字的保護,那麼可能在執行完 if 的條件判斷以後
// 另一個線程卻執行了 balance=balance-amount 修改了 balance 的值
// 而這個修改對這個線程是不可見的,因此可能致使這時 if 的條件已經不成立了
// 可是,這個線程卻繼續執行 balance=balance-amount,因此致使 balance 可能小於 0
// 去除 lock 塊能夠看出效果,程序會拋出異常
if (balance >= amount)
{
Thread.Sleep(5);
balance = balance - amount;
}
Console.WriteLine("Current Thread:" + Thread.CurrentThread.Name
+ " balance:" + balance.ToString() + " amount:" + amount);
}
}
internal void DoTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(r.Next(-50, 100));
}
}
}
internal class Test
{
static internal Thread[] threads = new Thread[10];
public static void Main()
{
Account acc = new Account(0);
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(acc.DoTransactions));
threads[i] = t;
threads[i].Name = i.ToString();
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
Console.ReadLine();
}
}
Lock 語法簡單易用。其本質是針對 Monitor.Enter() 和 Monitor.Exit() 的封裝,是一個語法糖!spa
當多個線程公用一個對象時,也會出現和公用代碼相似的問題,這就須要用到 System.Threading 中的 Monitor 類,咱們能夠稱之爲監視器,Monitor 提供了使線程共享資源的方案。
Monitor 類能夠鎖定一個對象,一個線程只有獲得這把鎖才能夠對該對象進行操做。 對象鎖機制保證了在可能引發混亂的狀況下,一個時刻只有一個線程能夠訪問這個對象。Monitor 必須和一個具體的對象相關聯,可是因爲它是一個靜態的類,因此不能使用它來定義對象,並且它的全部方法都是靜態的,不能使用對象來引用。
下面代碼說明了使用 Monitor 鎖定一個對象的情形:線程
// 表示對象的先進先出集合
Queue oQueue = new Queue();
try
{
// 如今 oQueue 對象只能被當前線程操縱了
Monitor.Enter(oQueue);
// do something......
}
catch
{
}
finally
{
// 釋放鎖
Monitor.Exit(oQueue);
}
如上所示, 當一個線程調用 Monitor.Enter() 方法鎖定一個對象時,這個對象就歸它全部了,其它線程想要訪問這個對象,只有等待它使用 Monitor.Exit() 方法釋放鎖。爲了保證線程最終都能釋放鎖,你能夠把 Monitor.Exit() 方法寫在 try-catch-finally 結構中的 finally 代碼塊裏。(Lock 關鍵字就是這個步驟的語法糖)
任何一個被 Monitor 鎖定的對象,內存中都保存着與它相關的一些信息:
當擁有對象鎖的線程準備釋放鎖時,它使用 Monitor.Pulse() 方法通知等待隊列中的第一個線程,因而該線程被轉移到預備隊列中,當對象鎖被釋放時,在預備隊列中的線程能夠當即得到對象鎖。
下面是一個展現如何使用 lock 關鍵字和 Monitor 類來實現線程的同步和通信的例子,是一個典型的生產者與消費者問題。
在本例中,生產者線程和消費者線程是交替進行的,生產者寫入一個數,消費者當即讀取而且顯示(註釋中介紹了該程序的精要所在)。
/// <summary>
/// 被操做的對象
/// </summary>
public class Cell
{
/// <summary>
/// Cell 對象裏的內容
/// </summary>
int cellContents;
/// <summary>
/// 狀態標誌: 爲 true 時能夠讀取,爲 false 則正在寫入
/// </summary>
bool readerFlag = false;
public int ReadFromCell()
{
lock (this)
{
if (!readerFlag)
{
try
{
// 等待 WriteToCell 方法中調用 Monitor.Pulse()方法
Monitor.Wait(this);
}
catch (SynchronizationLockException e)
{
Console.WriteLine(e);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
// 開始消費行爲
Console.WriteLine("Consume: {0}", cellContents);
Console.WriteLine();
// 重置 readerFlag 標誌,表示消費行爲已經完成
readerFlag = false;
// 通知 WriteToCell()方法(該方法在另一個線程中執行,等待中)
Monitor.Pulse(this);
}
return cellContents;
}
public void WriteToCell(int n)
{
lock (this)
{
if (readerFlag)
{
try
{
Monitor.Wait(this);
}
catch (SynchronizationLockException e)
{
// 當同步方法(指Monitor類除Enter以外的方法)在非同步的代碼區被調用
Console.WriteLine(e);
}
catch (ThreadInterruptedException e)
{
// 當線程在等待狀態的時候停止
Console.WriteLine(e);
}
}
cellContents = n;
Console.WriteLine("Produce: {0}", cellContents);
readerFlag = true;
Monitor.Pulse(this); // 通知另一個線程中正在等待的 ReadFromCell() 方法
}
}
}
/// <summary>
/// 生產者
/// </summary>
public class CellProd
{
/// <summary>
/// 被操做的 Cell 對象
/// </summary>
Cell cell;
/// <summary>
/// 生產者生產次數,初始化爲 1
/// </summary>
int quantity = 1;
public CellProd(Cell box, int request)
{
cell = box;
quantity = request;
}
public void ThreadRun()
{
for (int looper = 1; looper <= quantity; looper++)
{
// 生產者向操做對象寫入信息
cell.WriteToCell(looper);
}
}
}
/// <summary>
/// 消費者
/// </summary>
public class CellCons
{
Cell cell;
int quantity = 1;
public CellCons(Cell box, int request)
{
cell = box;
quantity = request;
}
public void ThreadRun()
{
int valReturned;
for (int looper = 1; looper <= quantity; looper++)
{
valReturned = cell.ReadFromCell(); // 消費者從操做對象中讀取信息
}
}
}
/// <summary>
/// 測試類
/// </summary>
public class MonitorSample
{
public static void Main(String[] args)
{
// 一個標誌位,若是是 0 表示程序沒有出錯,若是是 1 代表有錯誤發生
int result = 0;
// 下面使用 cell 初始化 CellProd 和 CellCons 兩個類,生產和消費次數均爲 20 次
Cell cell = new Cell();
CellProd prod = new CellProd(cell, 20);
CellCons cons = new CellCons(cell, 20);
Thread producer = new Thread(new ThreadStart(prod.ThreadRun));
Thread consumer = new Thread(new ThreadStart(cons.ThreadRun));
// 生產者線程和消費者線程都已經被建立,可是沒有開始執行
try
{
producer.Start();
consumer.Start();
producer.Join();
consumer.Join();
Console.ReadLine();
}
catch (ThreadStateException e)
{
// 當線程由於所處狀態的緣由而不能執行被請求的操做
Console.WriteLine(e);
result = 1;
}
catch (ThreadInterruptedException e)
{
// 當線程在等待狀態的時候停止
Console.WriteLine(e);
result = 1;
}
// 儘管 Main() 函數沒有返回值,但下面這條語句能夠向父進程返回執行結果
Environment.ExitCode = result;
}
}
這個簡單的例子解決了多線程應用程序中可能出現的大問題, 只要領悟瞭解決線程間衝突的基本方法,很容易把它應用到比較複雜的程序中去。