帶着問題去思考!大家好
介紹線程之前,我們先了解下線程管理。
首先,線程管理是操作系統的核心。
爲什麼要引入線程,什麼是線程及進程由什麼組成,進程是如何解決問題的?
在多道程序環境下,允許多個程序併發執行,此時它們將失去封閉性,並具有間斷性及不可再現性的特徵。爲此引入進程,以便更好的描述和控制程序的併發執行,實現操作系統的併發性和共享性
進程間的通信
指進程之間的信息交換。PV操作是低級通信方式,高級通信方式是指以較高的效率傳輸大量數據的通信方式。一般分爲三種
1:共享存儲:在共享空間進行寫/讀操作。需要使用同步互斥工具(如P.V操作),共享存儲分兩種:低級方式的共享是基於數據結構的共享,高級方式則是基於存儲區的共享。
2:消息傳遞:
直接通信方式:發送進程直接把消息發給接受進程,並將他掛在接收進程的消息緩衝隊列上,接受進程從消息緩衝隊列中取得消息,
間接通信方式:發送進程把消息發送到某個中間實體中,接收進程從中間實體中取得消息。
3:管道通信:指用於連接一個讀進程和一個寫進程實現他們之間通信的一個共享文件。pipe。
引入線程呢。是爲了減小程序在併發執行時所付出的時空開銷。
向線程傳遞參數
static void Main(string[] args) { var samlple = new ThreadSample(10); var threadOne = new Thread(samlple.CountNumber); threadOne.Name = "ThreadOne"; threadOne.Start(); threadOne.Join(); Console.WriteLine("-----------------------------"); var threadTwo = new Thread(Count); threadTwo.Name = "ThreadTwo"; threadTwo.Start(8); threadTwo.Join(); Console.WriteLine("-----------------------------"); var threadThree = new Thread(()=>CountNumber(12)); threadThree.Name = "threadThree"; threadThree.Start(); threadThree.Join(); Console.WriteLine("-----------------------------"); int i = 10; var threadFour = new Thread(() => PrintNumber(i)); i = 20; var threadFive = new Thread(() => PrintNumber(i)); threadFour.Start(); threadFive.Start(); } static void Count(object iterations) { CountNumber((int)iterations); } public static void CountNumber(int iterations) { for (int i = 0; i < iterations; i++) { Sleep(TimeSpan.FromSeconds(0.5)); Console.WriteLine($"{CurrentThread.Name} Prints {i}"); } } static void PrintNumber(int number) { Console.WriteLine(number); } class ThreadSample { private readonly int _iterations; public ThreadSample(int iterations) { this._iterations = iterations; } public void CountNumber() { for (int i = 0; i < _iterations; i++) { Sleep(TimeSpan.FromSeconds(0.5)); Console.WriteLine($"{CurrentThread.Name} Prints {i}"); } } }
線程傳參,C#中的線程只接收1個object類型的參數.
線程處理異常
try/catch如果包裹線程,那樣是捕獲不到的。應該放到線程代碼中。
線程優先級
Priority進行賦值,一般分佈Highest 。Lowest