From 2b2c36d991b7360ca2b2f181ed80101dd4b27ffe Mon Sep 17 00:00:00 2001 From: routersys Date: Fri, 9 Oct 2026 22:10:52 +0900 Subject: [PATCH] =?UTF-8?q?ScratchPool=E3=81=AE=E8=B2=B8=E3=81=97=E5=87=BA?= =?UTF-8?q?=E3=81=97=E3=82=92=E8=A9=A6=E9=A8=93=E3=81=A7=E5=9B=BA=E3=82=81?= =?UTF-8?q?=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ScratchPoolTests.cs | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 SpectralConvolution/SpectralConvolution.Tests/ScratchPoolTests.cs diff --git a/SpectralConvolution/SpectralConvolution.Tests/ScratchPoolTests.cs b/SpectralConvolution/SpectralConvolution.Tests/ScratchPoolTests.cs new file mode 100644 index 0000000..aaf1ccc --- /dev/null +++ b/SpectralConvolution/SpectralConvolution.Tests/ScratchPoolTests.cs @@ -0,0 +1,76 @@ +namespace SpectralConvolution.Tests; + +public sealed class ScratchPoolTests +{ + [Fact] + public void AReturnedItemIsHandedOutAgain() + { + var pool = new ScratchPool(2); + Item first; + using (var lease = pool.Rent()) + first = lease.Value; + + using var again = pool.Rent(); + + Assert.Same(first, again.Value); + } + + [Fact] + public void ItemsRentedAtTheSameTimeAreDistinct() + { + var pool = new ScratchPool(2); + using (pool.Rent()) + { + } + + using var first = pool.Rent(); + using var second = pool.Rent(); + + Assert.NotSame(first.Value, second.Value); + } + + [Fact] + public void AnItemReturnedBeyondTheCapacityIsDropped() + { + var pool = new ScratchPool(1); + var first = pool.Rent(); + var second = pool.Rent(); + var kept = first.Value; + var dropped = second.Value; + first.Dispose(); + second.Dispose(); + + using var rentedKept = pool.Rent(); + using var rentedNew = pool.Rent(); + + Assert.Same(kept, rentedKept.Value); + Assert.NotSame(kept, rentedNew.Value); + Assert.NotSame(dropped, rentedNew.Value); + } + + [Fact] + public void ARentedItemIsNeverSharedBetweenThreads() + { + var pool = new ScratchPool(Environment.ProcessorCount); + var collisions = 0; + + Parallel.For(0, 8, new ParallelOptions { MaxDegreeOfParallelism = 8 }, _ => + { + for (var round = 0; round < 20000; round++) + { + using var lease = pool.Rent(); + if (Interlocked.Exchange(ref lease.Value.Busy, 1) != 0) + Interlocked.Increment(ref collisions); + Thread.SpinWait(20); + Volatile.Write(ref lease.Value.Busy, 0); + } + }); + + Assert.Equal(0, collisions); + } + + sealed class Item + { + public int Busy; + } +}