Skip to content

Semaphore C# example not demonstrating usage clearly #5353

Open
@captaindakkar

Description

@captaindakkar

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<Thread> tl = new List<Thread>();
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 #5320 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Pri3Indicates issues/PRs that are low priorityarea-System.Threadingdoc-bugProblem with the content; needs to be fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions