- 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);
- var q = new Queue<T>();
- 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;
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/180720134669.html
来源: http://www.codesnippet.cn/detail/180720134669.html