60年代,在os中能擁有資源和獨立運行的基本單位是進程,然而隨著計算機技術的發展,進程出現了很多弊端,一是由于進程是資源擁有者,創建、撤消與切換存在較大的時空開銷,因此需要引入輕型進程;二是由于對稱多處理機(smp)出現,可以滿足多個運行單位,而多個進程并行開銷過大。
因此在80年代,出現了能獨立運行的基本單位——線程(threads)。
線程,有時被稱為輕量級進程(lightweight process,lwp),是程序執行流的最小單元。一個標準的線程由線程id,當前指令指針(pc),寄存器集合和堆棧組成。另外,線程是進程中的一個實體,是被系統獨立調度和分派的基本單位,線程自己不擁有系統資源,只擁有一點兒在運行中必不可少的資源,但它可與同屬一個進程的其它線程共享進程所擁有的全部資源。一個線程可以創建和撤消另一個線程,同一進程中的多個線程之間可以并發執行。由于線程之間的相互制約,致使線程在運行中呈現出間斷性。線程也有就緒、阻塞和運行三種基本狀態。就緒狀態是指線程具備運行的所有條件,邏輯上可以運行,在等待處理機;運行狀態是指線程占有處理機正在運行;阻塞狀態是指線程在等待一個事件(如某個信號量),邏輯上不可執行。每一個程序都至少有一個線程,若程序只有一個線程,那就是程序本身。
線程是程序中一個單一的順序控制流程。進程內一個相對獨立的、可調度的執行單元,是系統獨立調度和分派cpu的基本單位指運行中的程序的調度單位。在單個程序中同時運行多個線程完成不同的工作,稱為多線程。
一、線程簡義
1、進程與線程:進程作為操作系統執行程序的基本單位,擁有應用程序的資源,進程包含線程,進程的資源被線程共享,線程不擁有資源。
2、前臺線程和后臺線程:通過thread類新建線程默認為前臺線程。當所有前臺線程關閉時,所有的后臺線程也會被直接終止,不會拋出異常。
3、掛起(suspend)和喚醒(resume):由于線程的執行順序和程序的執行情況不可預知,所以使用掛起和喚醒容易發生死鎖的情況,在實際應用中應該盡量少用。
4、阻塞線程:join,阻塞調用線程,直到該線程終止。
5、終止線程:abort:拋出 threadabortexception 異常讓線程終止,終止后的線程不可喚醒。interrupt:拋出 threadinterruptexception 異常讓線程終止,通過捕獲異??梢岳^續執行。
6、線程優先級:abovenormal belownormal highest lowest normal,默認為normal。
二、線程的使用
線程函數通過委托傳遞,可以不帶參數,也可以帶參數(只能有一個參數),可以用一個類或結構體封裝參數。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
namespace test { class program { static void main( string [] args) { thread t1 = new thread( new threadstart(testmethod)); thread t2 = new thread( new parameterizedthreadstart(testmethod)); t1.isbackground = true ; t2.isbackground = true ; t1.start(); t2.start( "hello" ); console.readkey(); } public static void testmethod() { console.writeline( "不帶參數的線程函數" ); } public static void testmethod( object data) { string datastr = data as string ; console.writeline( "帶參數的線程函數,參數為:{0}" , datastr); } } } |
三、線程池
由于線程的創建和銷毀需要耗費一定的開銷,過多的使用線程會造成內存資源的浪費,出于對性能的考慮,于是引入了線程池的概念。線程池維護一個請求隊列,線程池的代碼從隊列提取任務,然后委派給線程池的一個線程執行,線程執行完不會被立即銷毀,這樣既可以在后臺執行任務,又可以減少線程創建和銷毀所帶來的開銷。
線程池線程默認為后臺線程(isbackground)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class program { static void main( string [] args) { //將工作項加入到線程池隊列中,這里可以傳遞一個線程參數 threadpool.queueuserworkitem(testmethod, "hello" ); console.readkey(); } public static void testmethod( object data) { string datastr = data as string ; console.writeline(datastr); } } |
四、task類
使用threadpool的queueuserworkitem()方法發起一次異步的線程執行很簡單,但是該方法最大的問題是沒有一個內建的機制讓你知道操作什么時候完成,有沒有一個內建的機制在操作完成后獲得一個返回值。為此,可以使用system.threading.tasks中的task類。
構造一個task<tresult>對象,并為泛型tresult參數傳遞一個操作的返回類型。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
class program { static void main( string [] args) { task<int32> t = new task<int32>(n => sum((int32)n), 1000); t.start(); t.wait(); console.writeline(t.result); console.readkey(); } private static int32 sum(int32 n) { int32 sum = 0; for (; n > 0; --n) checked { sum += n;} //結果太大,拋出異常 return sum; } } |
一個任務完成時,自動啟動一個新任務。
一個任務完成后,它可以啟動另一個任務,下面重寫了前面的代碼,不阻塞任何線程。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
class program { static void main( string [] args) { task<int32> t = new task<int32>(n => sum((int32)n), 1000); t.start(); //t.wait(); task cwt = t.continuewith(task => console.writeline( "the result is {0}" ,t.result)); console.readkey(); } private static int32 sum(int32 n) { int32 sum = 0; for (; n > 0; --n) checked { sum += n;} //結果溢出,拋出異常 return sum; } } |
五、委托異步執行
委托的異步調用:begininvoke() 和 endinvoke()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public delegate string mydelegate( object data); class program { static void main( string [] args) { mydelegate mydelegate = new mydelegate(testmethod); iasyncresult result = mydelegate.begininvoke( "thread param" , testcallback, "callback param" ); //異步執行完成 string resultstr = mydelegate.endinvoke(result); } //線程函數 public static string testmethod( object data) { string datastr = data as string ; return datastr; } //異步回調函數 public static void testcallback(iasyncresult data) { console.writeline(data.asyncstate); } } |
六、線程同步
1)原子操作(interlocked):幫助保護免受計劃程序切換上下文時某個線程正在更新可以由其他線程訪問的變量或者在單獨的處理器上同時執行兩個線程就可能出現的錯誤。 此類的成員不會引發異常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
class program { static int counter = 1; static void main( string [] args) { thread t1 = new thread( new threadstart(f1)); thread t2 = new thread( new threadstart(f2)); t1.start(); t2.start(); t1.join(); t2.join(); system.console.readkey(); } static void f1() { for ( int i = 0; i < 5; i++) { interlocked.increment( ref counter); system.console.writeline( "counter++ {0}" , counter); thread.sleep(10); } } static void f2() { for ( int i = 0; i < 5; i++) { interlocked.decrement( ref counter); system.console.writeline( "counter-- {0}" , counter); thread.sleep(10); } } } |
2)lock()語句:避免鎖定public類型,否則實例將超出代碼控制的范圍,定義private對象來鎖定。而自定義類推薦用私有的只讀靜態對象,比如:private static readonly object obj = new object();為什么要設置成只讀的呢?這時因為如果在lock代碼段中改變obj的值,其它線程就暢通無阻了,因為互斥鎖的對象變了,object.referenceequals必然返回false。array 類型提供 syncroot。許多集合類型也提供 syncroot。
3)monitor實現線程同步
通過monitor.enter() 和 monitor.exit()實現排它鎖的獲取和釋放,獲取之后獨占資源,不允許其他線程訪問。
還有一個tryenter方法,請求不到資源時不會阻塞等待,可以設置超時時間,獲取不到直接返回false。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public void monitorsomething() { try { monitor.enter(obj); dosomething(); } catch (exception ex) { } finally { monitor.exit(obj); } } |
4)readerwriterlock
當對資源操作讀多寫少的時候,為了提高資源的利用率,讓讀操作鎖為共享鎖,多個線程可以并發讀取資源,而寫操作為獨占鎖,只允許一個線程操作。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
class synchronizedcache { private readerwriterlockslim cachelock = new readerwriterlockslim(); private dictionary< int , string> innercache = new dictionary< int , string>(); public string read( int key) { cachelock.enterreadlock(); try { return innercache[key]; } finally { cachelock.exitreaderlock(); } } public void add( int key, string value) { cachelock.enterwritelock(); try { innercache.add(key, value); } finally { cachelock.exitwritelock(); } } public bool addwithtimeout( int key, string value, int timeout) { if (cachelock.tryenterwritelock(timeout)) { try { innercache.add(key, value); } finally { cachelock.exitreaderlock(); } return true ; } else { return false ; } } public addorupdatestatus addorupdate( int key, string value) { cachelock.enterupgradeablereadlock(); try { string result = null; if (innercache.trygetvalue(key, out result)) { if (result == value) { return addorupdatestatus.unchanged; } else { cachelock.enterwritelock(); try { innercache[key] = value; } finally { cachelock.exitwritelock(); } return addorupdatestatus.updated; } } else { cachelock.enterwritelock(); try { innercache.add(key, value); } finally { cachelock.exitwritelock(); } return addorupdatestatus.added; } } finally { cachelock.exitupgradeablereadlock(); } } public void delete ( int key) { cachelock.enterwritelock(); try { innercache. remove (key); } finally { cachelock.exitwritelock(); } } public enum addorupdatestatus { added, updated, unchanged }; } |
5)事件(event)類實現同步
事件類有兩種狀態,終止狀態和非終止狀態,終止狀態時調用waitone可以請求成功,通過set將時間狀態設置為終止狀態。
1).autoresetevent(自動重置事件)
2).manualresetevent(手動重置事件)
autoresetevent和manualresetevent這兩個類經常用到, 他們的用法很類似,但也有區別。set方法將信號置為發送狀態,reset方法將信號置為不發送狀態,waitone等待信號的發送??梢酝ㄟ^構造函數的參數值來決定其初始狀態,若為true則非阻塞狀態,為false為阻塞狀態。如果某個線程調用waitone方法,則當信號處于發送狀態時,該線程會得到信號, 繼續向下執行。其區別就在調用后,autoresetevent.waitone()每次只允許一個線程進入,當某個線程得到信號后,autoresetevent會自動又將信號置為不發送狀態,則其他調用waitone的線程只有繼續等待.也就是說,autoresetevent一次只喚醒一個線程;而manualresetevent則可以喚醒多個線程,因為當某個線程調用了manualresetevent.set()方法后,其他調用waitone的線程獲得信號得以繼續執行,而manualresetevent不會自動將信號置為不發送。也就是說,除非手工調用了manualresetevent.reset()方法,則manualresetevent將一直保持有信號狀態,manualresetevent也就可以同時喚醒多個線程繼續執行。
6)信號量(semaphore)
信號量是由內核對象維護的int變量,為0時,線程阻塞,大于0時解除阻塞,當一個信號量上的等待線程解除阻塞后,信號量計數+1。
線程通過waitone將信號量減1,通過release將信號量加1,使用很簡單。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
public thread thrd; //創建一個可授權2個許可證的信號量,且初始值為2 static semaphore sem = new semaphore(2, 2); public mythread( string name) { thrd = new thread( this .run); thrd.name = name; thrd.start(); } void run() { console.writeline(thrd.name + "正在等待一個許可證……" ); //申請一個許可證 sem.waitone(); console.writeline(thrd.name + "申請到許可證……" ); for ( int i = 0; i < 4 ; i++) { console.writeline(thrd.name + ": " + i); thread.sleep(1000); } console.writeline(thrd.name + " 釋放許可證……" ); //釋放 sem.release(); } } class mysemaphore { public static void main() { mythread mythrd1 = new mythread( "thrd #1" ); mythread mythrd2 = new mythread( "thrd #2" ); mythread mythrd3 = new mythread( "thrd #3" ); mythread mythrd4 = new mythread( "thrd #4" ); mythrd1.thrd.join(); mythrd2.thrd.join(); mythrd3.thrd.join(); mythrd4.thrd.join(); } } |
7)互斥體(mutex)
獨占資源,可以把mutex看作一個出租車,乘客看作線程。乘客首先等車,然后上車,最后下車。當一個乘客在車上時,其他乘客就只有等他下車以后才可以上車。而線程與c# mutex對象的關系也正是如此,線程使用mutex.waitone()方法等待c# mutex對象被釋放,如果它等待的c# mutex對象被釋放了,它就自動擁有這個對象,直到它調用mutex.releasemutex()方法釋放這個對象,而在此期間,其他想要獲取這個c# mutex對象的線程都只有等待。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
class test { /// <summary> /// 應用程序的主入口點。 /// </summary> [stathread] static void main( string [] args) { bool flag = false ; system.threading.mutex mutex = new system.threading.mutex( true , "test" , out flag); //第一個參數:true--給調用線程賦予互斥體的初始所屬權 //第一個參數:互斥體的名稱 //第三個參數:返回值,如果調用線程已被授予互斥體的初始所屬權,則返回true if (flag) { console.write( "running" ); } else { console.write( "another is running" ); system.threading.thread.sleep(5000); //線程掛起5秒鐘 environment.exit(1); //退出程序 } console.readline(); } } |
8)跨進程間的同步
通過設置同步對象的名稱就可以實現系統級的同步,不同應用程序通過同步對象的名稱識別不同同步對象。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
static void main( string [] args) { string mutexname = "interprocesssyncname" ; mutex syncnamed; //聲明一個已命名的互斥對象 try { syncnamed = mutex.openexisting(mutexname); //如果此命名互斥對象已存在則請求打開 } catch (waithandlecannotbeopenedexception) { syncnamed = new mutex( false , mutexname); //如果初次運行沒有已命名的互斥對象則創建一個 } task multesk = new task ( () => //多任務并行計算中的匿名方法,用委托也可以 { for (; ; ) //為了效果明顯而設計 { console.writeline( "當前進程等待獲取互斥訪問權......" ); syncnamed.waitone(); console.writeline( "獲取互斥訪問權,訪問資源完畢,按回車釋放互斥資料訪問權." ); console.readline(); syncnamed.releasemutex(); console.writeline( "已釋放互斥訪問權。" ); } } ); multesk.start(); multesk.wait(); } |
9)分布式的同步
可以使用redis任務隊列或者redis相關特性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
parallel. for (0, 1000000, i => { stopwatch sw1 = new stopwatch(); sw1.start(); if (redishelper.getredisoperation(). lock (key)) { var tt = int .parse(redishelper.getredisoperation().stringget( "calc" )); tt++; redishelper.getredisoperation().stringset( "calc" , tt.tostring()); redishelper.getredisoperation().unlock(key); } var v = sw1.elapsedmilliseconds; if (v >= 10 * 1000) { console.write( "f" ); } sw1.stop(); }); |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/yswenli/archive/2017/08/24/7421475.html