dotnet / dotnet/dotnet-api-docs

Semaphore C# example not demonstrating usage clearly

Open
#5,353 1 comment 0 reactions 0 assignees View on GitHub
area-System.Threading doc-bug Pri3
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

Hi, in the C# code sample for Semaphore class usage here https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphore?view=net-5.0, the main thread exits before the child threads complete execution. I suggest doing a Join() for all the child threads and keep the main thread alive to demonstrate the proper usage of semaphores. Perhaps by updating the code as follows, thanks.

List tl = new List();
for(int i = 1; i <= 5; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(Worker));

// Start the thread, passing the number.
//
t.Start(i);
tl.Add(t);
}

// Wait for half a second, to allow all the
// threads to start and to block on the semaphore.
//
Thread.Sleep(500);

// The main thread starts out holding the entire
// semaphore count. Calling Release(3) brings the
// semaphore count back to its maximum value, and
// allows the waiting threads to enter the semaphore,
// up to three at a time.
//
Console.WriteLine("Main thread calls Release(3).");
_pool.Release(3);

foreach (var t in tl)
{
t.Join();
}

Console.WriteLine("Main thread exits.");

_Originally posted by @captaindakkar in https://github.com/dotnet/dotnet-api-docs/issues/5320#issuecomment-782549337_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.