线程池

 

线程池(Thread Pooling)


  有许多应用线程的程序在等候事件的休眠状态中消耗了大量时间,Other threads may enter a sleeping state only to be awakened periodically to poll for a change or update status information. Thread pooling enables you to use threads more efficiently by providing your application with a pool of worker threads that are managed by the system. 至少一个线程监控着线程池中排列的所有wait操作状态。当一个等候操作执行完毕,线程池中一个worker线程就会执行相应的callback函数。


  你也可以把一些不需要wait操作的工作项添加到线程池中。要请求线程池中一个线程可以处理一个工作项的话,可以调用QueueUserWorkItem function. 该函数需要一个线程被选中时需要执行的函数作为参数。排队候,就没有办法撤销一个工作了。
  Timer-queue timers and registered wait operations 同样使用线程池. 他们的回调函数被排列到线程池中,你也可以通过 BindIoCompletionCallback 函数post异步I/O操作。异步I/O完成时,就会被线程池中一个线程执行callback函数。
  线程池是在第一次调用QueueUserWorkItem or BindIoCompletionCallback时创建的,或者一个timer-queue timer or registered wait operation queues a callback function.默认情况下,线程池中可创建的线程数为500,每个线程应用默认栈大小并按默认优先级执行。
  线程池中有两种类型的worker线程: I/O and non-I/O,I/O worker线程wait时有一个alertable wait状态,排队到I/O worker threads中的工作项可看为异步过程调用 (APC).
  A non-I/O worker thread waits on I/O completion ports,使用非I/O worker threads比使用I/O worker threads更有效率些。一次,你应该尽可能的使用非I/O worker threads。 如果仍有异步I/O请求未完成, I/O及non-I/O worker threads都不会exit。两种类型的线程都可被用来发起asynchronous I/O completion requests. 然而,如果异步I/O请求完成需要花费很长时间,就应当避免放置到非I/O worker threads中。
  要使用线程池,调用的工作项及所有函数必须保证是线程池安全的.安全的函数不应该假定其执行线程是dedicated or persistent的。通常情况下应当避免使用 thread local storage ,并避免把一个需要持久稳定线程的异步调用排队,如RegNotifyChangeKeyValue 函数。然而这些函数可以利用QueueUserWorkItem 的WT_EXECUTEINPERSISTENTTHREAD选项排队为一个持久稳定的worker thread。


注意:线程池不适合于single-threaded apartment (STA) 模式。


原文地址:https://www.cnblogs.com/chengxin1982/p/1553846.html