1. 程式人生 > >多線程編程學習筆記——線程同步(三)

多線程編程學習筆記——線程同步(三)

class gen hybird 進行 syn locks finall nal nbsp

接上文 多線程編程學習筆記——線程同步(一)

接上文 多線程編程學習筆記——線程同步(二)

七、使用Barrier類

Barrier類用於組織多個線程及時在某個時刻會面,其提供一個回調函數,每次線程調用了SignalAndWait方法後該回調函數就會被執行。

1.代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; //引入線程
using
System.Diagnostics; namespace ThreadSynchronousDemo { class Program { static Barrier barr = new Barrier(2,b=>Console.WriteLine(" 第 {0} 階段結束",b.CurrentPhaseNumber+1)); static void Main(string[] args) { Console.WriteLine("開始,Barrier 同步
"); var t = new Thread((() => working("線程 1 ", "第 1 個工作線程任務", 3))); var t2 = new Thread((() => working("線程 2","第 2 個工作線程任務", 6))); t.Start(); t2.Start(); Console.Read(); } static void working(string
name,string message,int seconds) { for (int i = 0; i < 3; i++) { Console.WriteLine("--------工作階段-------------"); Thread.Sleep(TimeSpan.FromSeconds(seconds)); Console.WriteLine("{0} 開始工作,內容:{1}",name,message); Thread.Sleep(TimeSpan.FromSeconds(seconds)); Console.WriteLine("{0} 的工作時間總計{1} 。結束工作,{2}", name,seconds, message); barr.SignalAndWait(); } } } }

2.運行結果。如下圖。

技術分享

創建了一個Barrier實例,指定了想要同步的兩個線程,兩個線程任何一個線程調用了SignalAndWait方法之後,都會調用回調函數打印出當前的處於什麽階段。這個類在多線程叠代計算中非常有用,可以在每個叠代結束之前執行一些操作,當最後一個線程調用SignalAndWait方法時,在叠代結束之前進行交互。

八、使用ReaderWriteLockSlim類

ReaderWriteLockSlim代表了一個管理資源訪問的鎖,允許多個線程同時讀取,但中獨占寫。

1.代碼如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; //引入線程
using System.Diagnostics;
 

namespace ThreadSynchronousDemo
{
    class Program
    {
        static ReaderWriterLockSlim rws = new ReaderWriterLockSlim();
        static List<int> list = new List<int>();     

        static void Main(string[] args)
        {
            Console.WriteLine("開始,ReaderWriterLockSlim 同步");      

            var t = new Thread(Read) { IsBackground=true};
            var t2 = new Thread(Read) { IsBackground = true };
            var t3 = new Thread(Read) { IsBackground = true };
 

            var t4 = new Thread((() => Write("線程 1 "))) { IsBackground = true };
            var t5 = new Thread((() => Write("線程 2"))) { IsBackground = true };
            //讀取數據線程
            t.Start();
            t2.Start();
            t3.Start();
            //寫入數據線程
            t4.Start();
            t5.Start();
            Console.Read();
        } 

        static void Read()
        {
            Console.WriteLine("--------從List中讀取數據-------------");
            while (true)
            {
                try
                {
                    rws.EnterReadLock();
                    foreach (var item in list)
                    {
                        Console.WriteLine("讀取數據內容:{0}", item);
                        Thread.Sleep(TimeSpan.FromSeconds(1));
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    rws.ExitReadLock();
                }         
            } 
        }

        static void Write(string threadName)
        {
            Console.WriteLine("--------往List中寫數據-------------");
            while (true)
            {
                try
                {
                    int newInt = new Random().Next(1, 100);
                    rws.EnterUpgradeableReadLock();
                    if(!list.Contains(newInt))
                    {
                        //如果List中沒有該數據,則寫入
                        try
                        {
                            rws.EnterWriteLock();
                            list.Add(newInt);
                            Console.WriteLine("{0} 寫入數據內容:{1}", threadName,newInt);
                        }
                        finally
                        {
                            rws.ExitWriteLock();
                        }                     

                        Thread.Sleep(TimeSpan.FromSeconds(1));                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    rws.ExitUpgradeableReadLock();
                }
            }

        }
    }

}

2.程序運行結果,發下圖。

技術分享

程序啟動後,直接運行五個線程,其中三個線程從集合中讀取數據,二個線程往集合中寫數據。

讀鎖允許多線程同時讀取數據,寫鎖則在釋放之前阻塞了其余的所有線程的操作。當線程獲取了讀鎖,從集合中讀取數據時,還要判斷當前集合上是否有寫鎖要寫數據,如果有寫鎖則會阻塞線程進行讀取數據,從而會浪費時間。所以本例中使用了EnterUpgradeabledReadLock和ExitUpgradeabledReadLock方法,先獲取讀鎖,然後讀數據,如果要修改集合中的數據,則把鎖升級成ReaderWriterLock然後進行寫數據,最後 使用ExitWriteLock退出鎖。

九、使用SpinWait類

SpinWait是一個混合同步構造,即先使用用戶模式等待一段時間,然後切換到內核模式,以節省CPU時間。

1.代碼如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; //引入線程
using System.Diagnostics; 

namespace ThreadSynchronousDemo
{
    class Program
    {
        static volatile bool isCompleted=false;       

        static void Main(string[] args)
        {
            Console.WriteLine("開始,SpinWait 同步");      

            var t = new Thread(UserModeWait);
            var t2 = new Thread(HybirdSpinWait) ;
            Console.WriteLine("開始,運行用戶模式");

            t.Start();
            Thread.Sleep(50);
            isCompleted = true;
            Thread.Sleep(TimeSpan.FromSeconds(5));
            isCompleted = false;
            Console.WriteLine("開始,運行內核模式");
            t2.Start();

            Thread.Sleep(TimeSpan.FromSeconds(5));
            isCompleted = true;
            Console.Read();
        }
 

        static void UserModeWait()
        {
            Console.WriteLine("--------用戶模式 等待-------------");
            while (!isCompleted)
            {
                        Console.Write("");
                        Thread.Sleep(TimeSpan.FromSeconds(1));   
            }

            Console.WriteLine();
            Console.WriteLine("用戶模式 等待結束");
        }

        static void HybirdSpinWait()
        {
            var spin = new SpinWait();
            Console.WriteLine("--------內核模式-------------");
            while (!isCompleted)
            {

                spin.SpinOnce();
               // NextSpinWillYield:其決定了調用SpinOnce方法的線程是否應該讓出CPU
                Console.WriteLine("是否應該讓出CPU :{0}",spin.NextSpinWillYield);
            }         

            Console.WriteLine("內核模式 結束");
        }
    }
}

2.程序運行結果,如下2圖。

技術分享

技術分享

程序中我們有一個執行無限循環的線程,在50ms之後主線程會設置isCompleted為true。我們可以在windows資源管理器,查看CPU的負載情況。

多線程編程學習筆記——線程同步(三)