ConcurrentExclusiveSchedulerPair.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // ConcurrentExclusiveSchedulerPair.cs
  2. //
  3. // Copyright (c) 2011 Jérémie "garuma" Laval
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. //
  24. using System;
  25. using System.Threading;
  26. using System.Collections.Generic;
  27. using System.Collections.Concurrent;
  28. namespace System.Threading.Tasks
  29. {
  30. public class ConcurrentExclusiveSchedulerPair : IDisposable
  31. {
  32. readonly int maxConcurrencyLevel;
  33. readonly int maxItemsPerTask;
  34. readonly TaskScheduler target;
  35. readonly TaskFactory factory;
  36. readonly Action taskHandler;
  37. readonly ConcurrentQueue<Task> concurrentTasks = new ConcurrentQueue<Task> ();
  38. readonly ConcurrentQueue<Task> exclusiveTasks = new ConcurrentQueue<Task> ();
  39. readonly ReaderWriterLockSlim rwl = new ReaderWriterLockSlim ();
  40. readonly TaskCompletionSource<object> completion = new TaskCompletionSource<object> ();
  41. readonly InnerTaskScheduler concurrent;
  42. readonly InnerTaskScheduler exclusive;
  43. int numTask;
  44. class InnerTaskScheduler : TaskScheduler
  45. {
  46. readonly ConcurrentExclusiveSchedulerPair scheduler;
  47. readonly ConcurrentQueue<Task> queue;
  48. public InnerTaskScheduler (ConcurrentExclusiveSchedulerPair scheduler,
  49. ConcurrentQueue<Task> queue)
  50. {
  51. this.scheduler = scheduler;
  52. this.queue = queue;
  53. }
  54. public override int MaximumConcurrencyLevel {
  55. get {
  56. return scheduler.maxConcurrencyLevel;
  57. }
  58. }
  59. protected override void QueueTask (Task t)
  60. {
  61. scheduler.DoQueue (t, queue);
  62. }
  63. protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
  64. {
  65. if (task.Status != TaskStatus.Created)
  66. return false;
  67. task.RunSynchronously (scheduler.target);
  68. return true;
  69. }
  70. public void Execute (Task t)
  71. {
  72. TryExecuteTask (t);
  73. }
  74. [MonoTODO ("Only useful for debugger support")]
  75. protected override IEnumerable<Task> GetScheduledTasks ()
  76. {
  77. throw new NotImplementedException ();
  78. }
  79. }
  80. public ConcurrentExclusiveSchedulerPair () : this (TaskScheduler.Current)
  81. {
  82. }
  83. public ConcurrentExclusiveSchedulerPair (TaskScheduler taskScheduler) : this (taskScheduler, taskScheduler.MaximumConcurrencyLevel)
  84. {
  85. }
  86. public ConcurrentExclusiveSchedulerPair (TaskScheduler taskScheduler, int maxConcurrencyLevel)
  87. : this (taskScheduler, maxConcurrencyLevel, -1)
  88. {
  89. }
  90. public ConcurrentExclusiveSchedulerPair (TaskScheduler taskScheduler, int maxConcurrencyLevel, int maxItemsPerTask)
  91. {
  92. this.target = taskScheduler;
  93. this.maxConcurrencyLevel = maxConcurrencyLevel;
  94. this.maxItemsPerTask = maxItemsPerTask;
  95. this.factory = new TaskFactory (taskScheduler);
  96. this.taskHandler = InternalTaskProcesser;
  97. this.concurrent = new InnerTaskScheduler (this, concurrentTasks);
  98. this.exclusive = new InnerTaskScheduler (this, exclusiveTasks);
  99. }
  100. public void Complete ()
  101. {
  102. completion.SetResult (null);
  103. }
  104. public TaskScheduler ConcurrentScheduler {
  105. get {
  106. return concurrent;
  107. }
  108. }
  109. public TaskScheduler ExclusiveScheduler {
  110. get {
  111. return exclusive;
  112. }
  113. }
  114. public Task Completion {
  115. get {
  116. return completion.Task;
  117. }
  118. }
  119. public void Dispose ()
  120. {
  121. Dispose (true);
  122. }
  123. [MonoTODO]
  124. protected virtual void Dispose (bool disposing)
  125. {
  126. }
  127. void DoQueue (Task task, ConcurrentQueue<Task> queue)
  128. {
  129. queue.Enqueue (task);
  130. SpinUpTasks ();
  131. }
  132. void InternalTaskProcesser ()
  133. {
  134. Task task;
  135. int times = 0;
  136. const int lockWaitTime = 2;
  137. while (!concurrentTasks.IsEmpty || !exclusiveTasks.IsEmpty) {
  138. if (maxItemsPerTask != -1 && ++times == maxItemsPerTask)
  139. break;
  140. bool locked = false;
  141. try {
  142. if (!concurrentTasks.IsEmpty && rwl.TryEnterReadLock (lockWaitTime)) {
  143. locked = true;
  144. while (concurrentTasks.TryDequeue (out task)) {
  145. RunTask (task);
  146. }
  147. }
  148. } finally {
  149. if (locked) {
  150. rwl.ExitReadLock ();
  151. locked = false;
  152. }
  153. }
  154. try {
  155. if (!exclusiveTasks.IsEmpty && rwl.TryEnterWriteLock (lockWaitTime)) {
  156. locked = true;
  157. while (exclusiveTasks.TryDequeue (out task)) {
  158. RunTask (task);
  159. }
  160. }
  161. } finally {
  162. if (locked) {
  163. rwl.ExitWriteLock ();
  164. }
  165. }
  166. }
  167. // TODO: there's a race here, task adding + spinup check may be done while here
  168. Interlocked.Decrement (ref numTask);
  169. }
  170. void SpinUpTasks ()
  171. {
  172. int currentTaskNumber;
  173. do {
  174. currentTaskNumber = numTask;
  175. if (currentTaskNumber >= maxConcurrencyLevel)
  176. return;
  177. } while (Interlocked.CompareExchange (ref numTask, currentTaskNumber + 1, currentTaskNumber) != currentTaskNumber);
  178. factory.StartNew (taskHandler);
  179. }
  180. void RunTask (Task task)
  181. {
  182. concurrent.Execute (task);
  183. }
  184. }
  185. }