TPL入門

27

description

2011/09/17 Hokuriku.NET C# -TPL入門- セッション資料

Transcript of TPL入門

Page 1: TPL入門
Page 2: TPL入門
Page 3: TPL入門
Page 4: TPL入門

堅牢性 信頼性 応答性

Page 5: TPL入門
Page 6: TPL入門

堅牢性 信頼性 応答性

Page 7: TPL入門

堅牢性 信頼性 応答性

Page 8: TPL入門
Page 9: TPL入門
Page 10: TPL入門
Page 11: TPL入門
Page 12: TPL入門

1. using System;2. using System.Linq;3. using System.Threading;4.

5. namespace ConsoleApplication6. {7. class Program8. {9. static void Main()10. {11. int lower = 0;12. int upper = 10000;13. var source = Enumerable.Range(lower, upper).ToArray();14. int chunk = (upper - lower) / Environment.ProcessorCount;15. var threads = new Thread[Environment.ProcessorCount];16.

17. for (int i = 0; i < threads.Length; i++)18. {19. int start = chunk * i + lower;20. int end = i < threads.Length - 121. ? start + chunk22. : upper;23. threads[i] = new Thread(() =>24. {25. for (int j = start; j < end; j++)26. {27. //----- Do Something28. Console.WriteLine(source[j]);29. }30. });31. }32.

33. foreach (var thread in threads) thread.Start();34. foreach (var thread in threads) thread.Join();35. }36. }37. }

Page 13: TPL入門

1. using System;2. using System.Linq;3. using System.Threading;4.

5. namespace ConsoleApplication6. {7. class Program8. {9. static void Main()10. {11. int lower = 0;12. int upper = 10000;13. var source = Enumerable.Range(lower, upper).ToArray();14. int chunk = (upper - lower) / Environment.ProcessorCount;15. var threads = new Thread[Environment.ProcessorCount];16.

17. for (int i = 0; i < threads.Length; i++)18. {19. int start = chunk * i + lower;20. int end = i < threads.Length - 121. ? start + chunk22. : upper;23. threads[i] = new Thread(() =>24. {25. for (int j = start; j < end; j++)26. {27. //----- Do Something28. Console.WriteLine(source[j]);29. }30. });31. }32.

33. foreach (var thread in threads) thread.Start();34. foreach (var thread in threads) thread.Join();35. }36. }37. }

Page 14: TPL入門

1. using System;

2. using System.Linq;

3. using System.Threading.Tasks;

4.

5. namespace ConsoleApplication

6. {

7. class Program

8. {

9. static void Main()

10. {

11. int lower = 0;

12. int upper = 10000;

13. var source = Enumerable.Range(lower, upper).ToArray();

14. Parallel.For(lower, upper, index =>

15. {

16. //----- Do Something

17. Console.WriteLine(source[index]);

18. });

19. }

20. }

21. }

Page 15: TPL入門
Page 16: TPL入門
Page 17: TPL入門

実CPUに割り当てるスレッドの切り替え

タイムスライスの後に同じスレッドが割り当てられる場合は発生しない

Page 18: TPL入門
Page 19: TPL入門

CLR ThreadPool

UIThread

Global Queue

WorkerThread 1

LocalQueue 1

WorkerThread 2

LocalQueue 2

詳しくはWebで!!

Page 20: TPL入門
Page 21: TPL入門
Page 22: TPL入門

スレッド

コレクション

パーティション

スレッドプール

要素

Page 23: TPL入門
Page 24: TPL入門
Page 25: TPL入門
Page 27: TPL入門

Let’s enjoy TPL!!