using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
namespace SleepSort
{
public class SleepSort
{
static void Main(string[] args)
{
var xs
= new[] { 11,
215,
12,
1985,
12,
1203,
12,
152 };
var sorted = Sort(xs, x => x);
Console.Write("Sorted:");
foreach (var x in sorted)
Console.Write(" {0}", x);
Console.WriteLine();
Console.ReadKey(true);
}
public static IEnumerable<T> Sort<T>(IEnumerable<T> xs, Func<T, int> conv)
{
const int WEIGHT = 40000;
var ev
= new EventWaitHandle
(false, EventResetMode
.ManualReset);
ParameterizedThreadStart f = x => { ev.WaitOne(); Thread.SpinWait(conv((T)x) * WEIGHT); lock (q) { q.Enqueue((T)x); } };
var ts
= xs
.Select(x
=> { var t
= new Thread
(f
); t
.Start(x
); return t
; }).ToArray();
ev.Set();
foreach (var t in ts)
t.Join();
return q;
}
}
}
//csharp/6495