Improved XNA Thread Pool object

jwatte's picture

This post includes a thread pool class for the XNA Framework that works better on the Xbox than the thread pool class in the Compact CLR. The main thread can choose to get notified about task completion with a callback function, or by waiting on a pre-allocated wait handle, or do fire-and-forget on the thread tasks.

You typically only create a single ThreadPoolComponent in your application, and let all your threaded tasks run within this component. This allows for ideal thread balancing. If you have multiple components, they will not know how to share the CPU between them fairly.

Create the ThreadPoolComponent in your application constructor, and add it to your Components collection. The ThreadPool will deliver any completed tasks first in the component update order.

On Xbox, creates 3 threads. On PC, creates one or more threads, depending on the number of CPU cores. Always creates at least one thread. The thread tasks are assumed to be computationally expensive, so more threads than there are CPU cores is not recommended.

Add a task to the thread queue. When a thread is available, it will dequeue this task and run it. Once complete, the task will be marked complete, but your application won't be called back until the next time Update() is called (so that callbacks are from the main thread). You can pass in a previously allocated TaskContext, to allow for waiting on the task, if you want finer grain synchronization than Game.Update() callbacks.

Finally, this thread pool is engineered so that it will not generate any garbage during normal runtime, which is important when running under the Compact CLR used on the Xbox.

AttachmentSize
ParallelThreadPool.zip3.38 KB