Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 9f48bd2

Browse files
committed
Fix bug in Semaphore.NamedProducerConsumer test
The test schedules two tasks, each of which creates a Semaphore with the same name. One of the tasks releases count into the semaphore, and the other consumes it via WaitOne. If the first task ends up creating the semaphore first, there's no problem: the first task will end up blocking, and the second task will end up creating the same semaphore and releasing count into it. But if the second task ends up executing first, it could create the semaphore, release count into it, and destroy the semaphore, all before the first task constructs the semaphore. If that happens, the first task will construct an entirely different semaphore, and end up blocking until timeout, at which point the test will fail. This fix introduces a barrier that ensures neither task waits or releases until both tasks have constructed the shared semaphore.
1 parent 080d07d commit 9f48bd2

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

src/System.Threading/tests/SemaphoreTests.cs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,20 +173,23 @@ public void NamedProducerConsumer()
173173
{
174174
string name = Guid.NewGuid().ToString("N");
175175
const int NumItems = 5;
176+
var b = new Barrier(2);
176177
Task.WaitAll(
177178
Task.Factory.StartNew(() =>
178179
{
179-
using (Semaphore s = new Semaphore(0, Int32.MaxValue, name))
180+
using (var s = new Semaphore(0, int.MaxValue, name))
180181
{
182+
Assert.True(b.SignalAndWait(FailedWaitTimeout));
181183
for (int i = 0; i < NumItems; i++)
182-
Assert.True(s.WaitOne(1000));
184+
Assert.True(s.WaitOne(FailedWaitTimeout));
183185
Assert.False(s.WaitOne(0));
184186
}
185187
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default),
186188
Task.Factory.StartNew(() =>
187189
{
188-
using (Semaphore s = new Semaphore(0, Int32.MaxValue, name))
190+
using (var s = new Semaphore(0, int.MaxValue, name))
189191
{
192+
Assert.True(b.SignalAndWait(FailedWaitTimeout));
190193
for (int i = 0; i < NumItems; i++)
191194
s.Release();
192195
}

0 commit comments

Comments
 (0)