内部完全使用Monitor实现,理论上比使用WaitHandler的资源消耗更少,也更快。缺点是会损失一些功能。

Semaphore源码(btw:gotdotnet上面有一个ManagedThreadPool):
 1更轻量级的Semaphore、AutoResetEvent、ThreadPoolusing System;
 2更轻量级的Semaphore、AutoResetEvent、ThreadPoolusing System.Threading;
 3更轻量级的Semaphore、AutoResetEvent、ThreadPool
 4更轻量级的Semaphore、AutoResetEvent、ThreadPoolnamespace newsmth.Nineteen
 5

AutoResetEvent源码:
 1更轻量级的Semaphore、AutoResetEvent、ThreadPoolusing System;
 2更轻量级的Semaphore、AutoResetEvent、ThreadPoolusing System.Threading;
 3更轻量级的Semaphore、AutoResetEvent、ThreadPool
 4更轻量级的Semaphore、AutoResetEvent、ThreadPoolnamespace newsmth.Nineteen
 5

ThreadPool:
大家都知道,计算密集型应用和IO密集型应用很不同。
对计算密集型的应用,首先要保持活动线程有合适的数量,少了,多cpu机器有些cpu会闲,多了,丫又会做很多无用功在线程上下文切换上;其次,应该尽可能减少活动线程在等待某些条件时的上下文切换(如果这些条件出现非常频繁迅速的话),即用SpinWait并不断轮询,而不是Sleep或者等一个WaitHandler。
IO密集型则不同,一般情况下,这东西就跟放掉水池里的水,出水口越多,放的就越快。

说它只是个半成品,是只实现了这么一个架子,没有做什么优化,也没经过很好的测试。效率,俺猜,应该不比系统的线程池差。code project上有个功能爆强的ThreadPool,但是它是建立在WaitHandler上的。尽管“只有适合自己的才是最好的”,但是它的代码还是很推荐一读。

btw:多说两句ThreadPool中两个很关键但是很简单的数据结构,一,任务被压到ThreadPool中应该是先进先出的队列;线程的调度,应该是后进先出的stack。后者,让忙的线程更忙,闲的线程更闲,是保持活动线程数更小的重要手段,不幸的是,它常常被忽略。
  1更轻量级的Semaphore、AutoResetEvent、ThreadPoolusing System;
  2更轻量级的Semaphore、AutoResetEvent、ThreadPoolusing System.Collections.Generic;
  3更轻量级的Semaphore、AutoResetEvent、ThreadPoolusing System.Text;
  4更轻量级的Semaphore、AutoResetEvent、ThreadPoolusing System.Threading;
  5更轻量级的Semaphore、AutoResetEvent、ThreadPool
  6更轻量级的Semaphore、AutoResetEvent、ThreadPoolnamespace newsmth.Nineteen
  7

欢迎拍砖。

相关文章:

  • 2022-12-23
  • 2021-04-05
  • 2022-12-23
  • 2021-08-02
  • 2021-06-22
  • 2021-08-18
  • 2021-09-17
猜你喜欢
  • 2022-12-23
  • 2021-10-21
  • 2022-12-23
  • 2021-12-13
  • 2021-12-19
  • 2022-12-23
  • 2021-12-15
相关资源
相似解决方案