Skip to content

Instantly share code, notes, and snippets.

@ewilde
Created May 9, 2016 16:40
Show Gist options
  • Save ewilde/899afaa19426f8ba74d36cf770a428d3 to your computer and use it in GitHub Desktop.
Save ewilde/899afaa19426f8ba74d36cf770a428d3 to your computer and use it in GitHub Desktop.
public class TaskSchedulerPool
{
private readonly List<Lazy<TaskScheduler>> _taskSchedulers;
public TaskSchedulerPool(int maxSize)
{
_taskSchedulers = Enumerable.Range(1, maxSize)
.Select(
_ => new Lazy<TaskScheduler>(() => new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler))
.ToList();
}
public TaskScheduler GetTaskScheduler(object o)
{
var partition = Math.Abs(o.GetHashCode())%_taskSchedulers.Count;
return _taskSchedulers[partition].Value;
}
}
class Program
{
private static int run;
private static int counter1;
private static int counter2;
static void Main(string[] args)
{
var pool = new TaskSchedulerPool(4);
var key1 = "key1";
var key2 = "key2";
var cancel = new CancellationTokenSource();
for (var i = 0; i < 40000; i++)
{
var i1 = i;
Task.Factory.StartNew(() => LogResult("1", key1, ref counter1), cancel.Token, TaskCreationOptions.None, pool.GetTaskScheduler(key1));
Task.Factory.StartNew(() => LogResult("2", key2, ref counter2), cancel.Token, TaskCreationOptions.None, pool.GetTaskScheduler(key2));
}
Console.ReadLine();
}
static void LogResult(string message, string key, ref int counter)
{
Interlocked.Increment(ref run);
Interlocked.Increment(ref counter);
Debug.Assert(counter==1);
Console.WriteLine("{0}|{1}:{2} concurrency:{3}", run, message, key, counter);
Interlocked.Decrement(ref counter);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment