Chapter 8. Thread Pools

WHAT'S IN THIS CHAPTER?

  • Understanding the improved thread pool engine

  • Requesting work items to run in threads in the thread pool

  • Using lightweight synchronization primitives with threads

  • Coordinating worker threads

  • Using tasks instead of threads to queue jobs

  • Understanding local queues, work-stealing mechanisms, and fine-grained parallelism

  • Specifying a custom task scheduler

This chapter is about the changes in the Common Language Runtime (CLR) thread pool engine introduced by .NET Framework 4. It is important to understand the differences between using tasks and directly requesting work items to run in threads in the thread pool. If you have worked with the thread pool, you can take advantage of the new improvements and move your code to a task-based programming model. This chapter also provides an example of a customized task scheduler.

GOING DOWNSTAIRS FROM THE TASKS FLOOR

In previous chapters, you created tasks to parallelize the execution of code. In some cases, you didn't write statements to create Task instances; instead, you used .NET Framework 4's new classes and methods that created the necessary tasks to parallelize the execution. For example, Parallel.Invoke, Parallel.For, Parallel.ForEach, and PLINQ (among others) create tasks under the hood.

Figure 8-1 shows a simple staircase with three floors, Tasks, Threads, and CLR thread pool engine. The Tasks floor typically has some tasks assigned to threads and other tasks waiting to be assigned to threads. If ...

Get Professional Parallel Programming with C#: Master Parallel Extensions With .NET 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.