public void RacingClears() { int cores = CoreCount(); if (cores < 2) { cores = 2; } var threads = new Thread[cores]; var queue = new SlimConcurrentQueue <int>(); int done = 0; threads[0] = new Thread(() => { for (int x = 0; x != 1000000; ++x) { queue.Enqueue(x); } Interlocked.Increment(ref done); }); for (int i = 1; i != cores; ++i) { threads[i] = new Thread(() => { while (done == 0) { for (int x = 0; x != 1000; ++x) { queue.Clear(); } } }); } for (int i = 0; i < cores; ++i) { threads[i].Start(); } for (int i = 0; i < cores; ++i) { threads[i].Join(); } Assert.IsTrue(queue.IsEmpty); }
public void HalfDequeue() { int cores = CoreCount(); if (cores < 2) { cores = 2; } var threads = new Thread[cores]; var queue = new SlimConcurrentQueue <int>(); var secQueue = new TrackedConcurrentQueue <int>(); for (int i = 0; i != cores; ++i) { if (i % 2 == 0) { threads[i] = new Thread(obj => { int off = (int)obj; for (int x = 0; x != 100000; ++x) { queue.Enqueue(x * cores + off); } }); } else { threads[i] = new Thread(obj => { foreach (int taken in queue.DequeueAll()) { secQueue.Enqueue(taken); } }); } } for (int i = 0; i < cores; i += 2) { threads[i].Start(i); } for (int i = 1; i < cores; i += 2) { threads[i].Start(i); } for (int i = 0; i != cores; ++i) { threads[i].Join(); } Dictionary <int, int> dict = new Dictionary <int, int>(); for (int i = 0; i != cores; ++i) { dict[i] = -1; } secQueue.EnqueueRange(queue); foreach (int test in secQueue) { int bucket = test % cores; int last = dict[bucket]; Assert.IsTrue(test > last); dict[bucket] = last; } }