SynchronizedPool.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.Runtime
  5. {
  6. using System.Collections.Generic;
  7. using System.Security;
  8. using System.Security.Permissions;
  9. using System.Threading;
  10. // A simple synchronized pool would simply lock a stack and push/pop on return/take.
  11. //
  12. // This implementation tries to reduce locking by exploiting the case where an item
  13. // is taken and returned by the same thread, which turns out to be common in our
  14. // scenarios.
  15. //
  16. // Initially, all the quota is allocated to a global (non-thread-specific) pool,
  17. // which takes locks. As different threads take and return values, we record their IDs,
  18. // and if we detect that a thread is taking and returning "enough" on the same thread,
  19. // then we decide to "promote" the thread. When a thread is promoted, we decrease the
  20. // quota of the global pool by one, and allocate a thread-specific entry for the thread
  21. // to store it's value. Once this entry is allocated, the thread can take and return
  22. // it's value from that entry without taking any locks. Not only does this avoid
  23. // locks, but it affinitizes pooled items to a particular thread.
  24. //
  25. // There are a couple of additional things worth noting:
  26. //
  27. // It is possible for a thread that we have reserved an entry for to exit. This means
  28. // we will still have a entry allocated for it, but the pooled item stored there
  29. // will never be used. After a while, we could end up with a number of these, and
  30. // as a result we would begin to exhaust the quota of the overall pool. To mitigate this
  31. // case, we throw away the entire per-thread pool, and return all the quota back to
  32. // the global pool if we are unable to promote a thread (due to lack of space). Then
  33. // the set of active threads will be re-promoted as they take and return items.
  34. //
  35. // You may notice that the code does not immediately promote a thread, and does not
  36. // immediately throw away the entire per-thread pool when it is unable to promote a
  37. // thread. Instead, it uses counters (based on the number of calls to the pool)
  38. // and a threshold to figure out when to do these operations. In the case where the
  39. // pool to misconfigured to have too few items for the workload, this avoids constant
  40. // promoting and rebuilding of the per thread entries.
  41. //
  42. // You may also notice that we do not use interlocked methods when adjusting statistics.
  43. // Since the statistics are a heuristic as to how often something is happening, they
  44. // do not need to be perfect.
  45. //
  46. [Fx.Tag.SynchronizationObject(Blocking = false)]
  47. class SynchronizedPool<T> where T : class
  48. {
  49. const int maxPendingEntries = 128;
  50. const int maxPromotionFailures = 64;
  51. const int maxReturnsBeforePromotion = 64;
  52. const int maxThreadItemsPerProcessor = 16;
  53. Entry[] entries;
  54. GlobalPool globalPool;
  55. int maxCount;
  56. PendingEntry[] pending;
  57. int promotionFailures;
  58. public SynchronizedPool(int maxCount)
  59. {
  60. int threadCount = maxCount;
  61. int maxThreadCount = maxThreadItemsPerProcessor + SynchronizedPoolHelper.ProcessorCount;
  62. if (threadCount > maxThreadCount)
  63. {
  64. threadCount = maxThreadCount;
  65. }
  66. this.maxCount = maxCount;
  67. this.entries = new Entry[threadCount];
  68. this.pending = new PendingEntry[4];
  69. this.globalPool = new GlobalPool(maxCount);
  70. }
  71. object ThisLock
  72. {
  73. get
  74. {
  75. return this;
  76. }
  77. }
  78. public void Clear()
  79. {
  80. Entry[] entries = this.entries;
  81. for (int i = 0; i < entries.Length; i++)
  82. {
  83. entries[i].value = null;
  84. }
  85. globalPool.Clear();
  86. }
  87. void HandlePromotionFailure(int thisThreadID)
  88. {
  89. int newPromotionFailures = this.promotionFailures + 1;
  90. if (newPromotionFailures >= maxPromotionFailures)
  91. {
  92. lock (ThisLock)
  93. {
  94. this.entries = new Entry[this.entries.Length];
  95. globalPool.MaxCount = maxCount;
  96. }
  97. PromoteThread(thisThreadID);
  98. }
  99. else
  100. {
  101. this.promotionFailures = newPromotionFailures;
  102. }
  103. }
  104. bool PromoteThread(int thisThreadID)
  105. {
  106. lock (ThisLock)
  107. {
  108. for (int i = 0; i < this.entries.Length; i++)
  109. {
  110. int threadID = this.entries[i].threadID;
  111. if (threadID == thisThreadID)
  112. {
  113. return true;
  114. }
  115. else if (threadID == 0)
  116. {
  117. globalPool.DecrementMaxCount();
  118. this.entries[i].threadID = thisThreadID;
  119. return true;
  120. }
  121. }
  122. }
  123. return false;
  124. }
  125. void RecordReturnToGlobalPool(int thisThreadID)
  126. {
  127. PendingEntry[] localPending = this.pending;
  128. for (int i = 0; i < localPending.Length; i++)
  129. {
  130. int threadID = localPending[i].threadID;
  131. if (threadID == thisThreadID)
  132. {
  133. int newReturnCount = localPending[i].returnCount + 1;
  134. if (newReturnCount >= maxReturnsBeforePromotion)
  135. {
  136. localPending[i].returnCount = 0;
  137. if (!PromoteThread(thisThreadID))
  138. {
  139. HandlePromotionFailure(thisThreadID);
  140. }
  141. }
  142. else
  143. {
  144. localPending[i].returnCount = newReturnCount;
  145. }
  146. break;
  147. }
  148. else if (threadID == 0)
  149. {
  150. break;
  151. }
  152. }
  153. }
  154. void RecordTakeFromGlobalPool(int thisThreadID)
  155. {
  156. PendingEntry[] localPending = this.pending;
  157. for (int i = 0; i < localPending.Length; i++)
  158. {
  159. int threadID = localPending[i].threadID;
  160. if (threadID == thisThreadID)
  161. {
  162. return;
  163. }
  164. else if (threadID == 0)
  165. {
  166. lock (localPending)
  167. {
  168. if (localPending[i].threadID == 0)
  169. {
  170. localPending[i].threadID = thisThreadID;
  171. return;
  172. }
  173. }
  174. }
  175. }
  176. if (localPending.Length >= maxPendingEntries)
  177. {
  178. this.pending = new PendingEntry[localPending.Length];
  179. }
  180. else
  181. {
  182. PendingEntry[] newPending = new PendingEntry[localPending.Length * 2];
  183. Array.Copy(localPending, newPending, localPending.Length);
  184. this.pending = newPending;
  185. }
  186. }
  187. public bool Return(T value)
  188. {
  189. int thisThreadID = Thread.CurrentThread.ManagedThreadId;
  190. if (thisThreadID == 0)
  191. {
  192. return false;
  193. }
  194. if (ReturnToPerThreadPool(thisThreadID, value))
  195. {
  196. return true;
  197. }
  198. return ReturnToGlobalPool(thisThreadID, value);
  199. }
  200. bool ReturnToPerThreadPool(int thisThreadID, T value)
  201. {
  202. Entry[] entries = this.entries;
  203. for (int i = 0; i < entries.Length; i++)
  204. {
  205. int threadID = entries[i].threadID;
  206. if (threadID == thisThreadID)
  207. {
  208. if (entries[i].value == null)
  209. {
  210. entries[i].value = value;
  211. return true;
  212. }
  213. else
  214. {
  215. return false;
  216. }
  217. }
  218. else if (threadID == 0)
  219. {
  220. break;
  221. }
  222. }
  223. return false;
  224. }
  225. bool ReturnToGlobalPool(int thisThreadID, T value)
  226. {
  227. RecordReturnToGlobalPool(thisThreadID);
  228. return globalPool.Return(value);
  229. }
  230. public T Take()
  231. {
  232. int thisThreadID = Thread.CurrentThread.ManagedThreadId;
  233. if (thisThreadID == 0)
  234. {
  235. return null;
  236. }
  237. T value = TakeFromPerThreadPool(thisThreadID);
  238. if (value != null)
  239. {
  240. return value;
  241. }
  242. return TakeFromGlobalPool(thisThreadID);
  243. }
  244. T TakeFromPerThreadPool(int thisThreadID)
  245. {
  246. Entry[] entries = this.entries;
  247. for (int i = 0; i < entries.Length; i++)
  248. {
  249. int threadID = entries[i].threadID;
  250. if (threadID == thisThreadID)
  251. {
  252. T value = entries[i].value;
  253. if (value != null)
  254. {
  255. entries[i].value = null;
  256. return value;
  257. }
  258. else
  259. {
  260. return null;
  261. }
  262. }
  263. else if (threadID == 0)
  264. {
  265. break;
  266. }
  267. }
  268. return null;
  269. }
  270. T TakeFromGlobalPool(int thisThreadID)
  271. {
  272. RecordTakeFromGlobalPool(thisThreadID);
  273. return globalPool.Take();
  274. }
  275. struct Entry
  276. {
  277. public int threadID;
  278. public T value;
  279. }
  280. struct PendingEntry
  281. {
  282. public int returnCount;
  283. public int threadID;
  284. }
  285. static class SynchronizedPoolHelper
  286. {
  287. public static readonly int ProcessorCount = GetProcessorCount();
  288. [Fx.Tag.SecurityNote(Critical = "Asserts in order to get the processor count from the environment", Safe = "This data isn't actually protected so it's ok to leak")]
  289. [SecuritySafeCritical]
  290. [EnvironmentPermission(SecurityAction.Assert, Read = "NUMBER_OF_PROCESSORS")]
  291. static int GetProcessorCount()
  292. {
  293. return Environment.ProcessorCount;
  294. }
  295. }
  296. [Fx.Tag.SynchronizationObject(Blocking = false)]
  297. class GlobalPool
  298. {
  299. Stack<T> items;
  300. int maxCount;
  301. public GlobalPool(int maxCount)
  302. {
  303. this.items = new Stack<T>();
  304. this.maxCount = maxCount;
  305. }
  306. public int MaxCount
  307. {
  308. get
  309. {
  310. return maxCount;
  311. }
  312. set
  313. {
  314. lock (ThisLock)
  315. {
  316. while (items.Count > value)
  317. {
  318. items.Pop();
  319. }
  320. maxCount = value;
  321. }
  322. }
  323. }
  324. object ThisLock
  325. {
  326. get
  327. {
  328. return this;
  329. }
  330. }
  331. public void DecrementMaxCount()
  332. {
  333. lock (ThisLock)
  334. {
  335. if (items.Count == maxCount)
  336. {
  337. items.Pop();
  338. }
  339. maxCount--;
  340. }
  341. }
  342. public T Take()
  343. {
  344. if (this.items.Count > 0)
  345. {
  346. lock (ThisLock)
  347. {
  348. if (this.items.Count > 0)
  349. {
  350. return this.items.Pop();
  351. }
  352. }
  353. }
  354. return null;
  355. }
  356. public bool Return(T value)
  357. {
  358. if (this.items.Count < this.MaxCount)
  359. {
  360. lock (ThisLock)
  361. {
  362. if (this.items.Count < this.MaxCount)
  363. {
  364. this.items.Push(value);
  365. return true;
  366. }
  367. }
  368. }
  369. return false;
  370. }
  371. public void Clear()
  372. {
  373. lock (ThisLock)
  374. {
  375. this.items.Clear();
  376. }
  377. }
  378. }
  379. }
  380. }