OS:Windows 10
.NET Framework 4.6
.NET Framework 4.0 新增System.Collections.Concurrent命名空間,此命名空間中提供多種執行緒安全(Thread-Safe)的集合,可以搭配TPL (Task Parallel Library) 平行處理的功能來進行運算,很適合用來撰寫多執行緒的應用程式。
使用這些執行緒安全(Thread-Safe)的類別的好處是,你不用自行鎖定資源;不用管CPU的數量有多少;也不用管多執行緒的race condition問題…..,這些都由System.Collections.Concurrent命名空間下的類別幫你處理,你只要處理程式的邏輯就好。
以下範例使用ConcurrentQueue<T>做1加到100的累加運算:
class TestClass {
static void Main( string [ ] args ) {
//建立ConcurrentQueue
ConcurrentQueue<int> myQ = new ConcurrentQueue<int>( );
//將1~100加入Queue
for ( int i = 1 ; i <= 100 ; i++ ) {
myQ.Enqueue( i );
}
int total = 0; //存放 1加到100的結果
Action myAction = ( ) => {
int sum = 0; //每個Thread個別累加運算的結果
int number; //要累加的數值
while ( myQ.TryDequeue( out number ) ) {
//累加到sum
sum += number;
//印出執行緒代號與要累加的數值
Console.WriteLine( "Thread ID = {0} , Value= {1} " ,
Environment.CurrentManagedThreadId , number );
}
//將每個Thread個別累加運算的結果,累加到total
Interlocked.Add( ref total , sum );
};
//指派四條Thread做累加運算
Parallel.Invoke( myAction , myAction , myAction , myAction );
//印出Processor數量
Console.WriteLine( "Processor Count = {0}" , Environment.ProcessorCount );
Console.WriteLine( "Total = {0}" , total );
Console.ReadLine( );
}
}
static void Main( string [ ] args ) {
//建立ConcurrentQueue
ConcurrentQueue<int> myQ = new ConcurrentQueue<int>( );
//將1~100加入Queue
for ( int i = 1 ; i <= 100 ; i++ ) {
myQ.Enqueue( i );
}
int total = 0; //存放 1加到100的結果
Action myAction = ( ) => {
int sum = 0; //每個Thread個別累加運算的結果
int number; //要累加的數值
while ( myQ.TryDequeue( out number ) ) {
//累加到sum
sum += number;
//印出執行緒代號與要累加的數值
Console.WriteLine( "Thread ID = {0} , Value= {1} " ,
Environment.CurrentManagedThreadId , number );
}
//將每個Thread個別累加運算的結果,累加到total
Interlocked.Add( ref total , sum );
};
//指派四條Thread做累加運算
Parallel.Invoke( myAction , myAction , myAction , myAction );
//印出Processor數量
Console.WriteLine( "Processor Count = {0}" , Environment.ProcessorCount );
Console.WriteLine( "Total = {0}" , total );
Console.ReadLine( );
}
}
執行結果:
// 略
Thread ID = 5 , Value= 98
Thread ID = 5 , Value= 99
Thread ID = 5 , Value= 100
Thread ID = 3 , Value= 92
Thread ID = 4 , Value= 90
Thread ID = 1 , Value= 91
Processor Count = 4
Total = 5050
Thread ID = 5 , Value= 98
Thread ID = 5 , Value= 99
Thread ID = 5 , Value= 100
Thread ID = 3 , Value= 92
Thread ID = 4 , Value= 90
Thread ID = 1 , Value= 91
Processor Count = 4
Total = 5050
沒有留言:
張貼留言