Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 656873
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T22:45:43+00:00 2026-05-13T22:45:43+00:00

I have multiple threads that share use of a semaphore. Thread A holds the

  • 0

I have multiple threads that share use of a semaphore. Thread A holds the semaphore (using lock) and threads B and C are waiting on that same semaphore (also using lock). The threads share global variables, etc.

Is there a technique in C# that I can use to shut down thread B? I can set a flag in A and have thread B check that flag and exit as soon as it gets control of the semaphore, but I don’t know of any technique to allow thread A to yield the semaphore to thread B (and get it back when thread B exits) without the risk of thread C seizing control.

Anyone have any suggestions how to address this design problem? I can rewrite the program as necessary if I am approaching this incorrectly.

[Edit]
A commenter has pointed out that I am using the wrong terminology. The commenter is correct – I am using a critical section, but given that everything is running in a single process, in this example critical sections are functionally equivalent to the more general term ‘semaphore’.

[Edit]
Someone asked for more details, so here it is.

There can be multiple threads executing Code A. There’s only ever one thread executing Code B.

Code A:

private static Thread workerThread = null;

lock (lockObject)
{
    ... do some work ...

    if (...condition...)
    {
        if (workerThread != null)
        {
            // Kill the worker thread and continue only after it is dead.
            quitWorkerThread = true;
            // Wait for the thread to die.
            while (workerThread.IsAlive)
            {
                Thread.Sleep(50);
            }
            workerThread = null;
            quitWorkerThread = false;
        } // if (workerThread != null)
    } // if (...condition...)

    ... do some more work ...

    if (...condition...)
    {
        if (workerThread == null)
        {
            // Start the worker thread.
            workerThread = new Thread(WorkerThread);
            workerThread.Start();
        } // if (workerThread == null)
    } // if (...condition...)

    ... do even more work ...

} // lock (lockObject)

Code B:

private void WorkerThread()
{
    while (true)
    {
        if (quitWorkerThread)
        {
            return;
        }

        Thread.Sleep (2000);

        if (quitWorkerThread)
        {
            return;
        }

        lock(lockObject)
        {
            if (quitWorkerThread)
            {
                return;
            }
            ... do some work ...
        } // lock(lockObject)
    } // while (true)
} // WorkerThread

I suspect that a variant of Aaron’s solution will be what I use. I was mostly hoping there was somewhat more elegant solution was available, but I suspect that like everything else about this project, it’s all brute force and corner cases :-(.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T22:45:43+00:00Added an answer on May 13, 2026 at 10:45 pm

    I’m fairly certain that there’s no way to yield control to a specific thread, which seems to be what you’re trying to do. You can only yield, period – it’s up to the Windows scheduler to decide what thread gets to run next.

    The situation is that you have three threads, A, B, and C. A has the lock, B and C are waiting for it, and you want a way to guarantee that B gets to executed next.

    The obvious solution is to use more than one lock and/or sync primitive. You can combine the semantics of lock with a ManualResetEvent. Make thread C wait for both the event and the critical section, but thread B only has to wait for the critical section. Under normal circumstances, you signal the event just before releasing the lock, which leaves it up to the OS to decide which thread to execute. In the special case, you don’t signal the event at all, leaving thread B to execute while C is still blocked.

    Once B is done, then you signal the event to let C finish.


    An (untested) example would be:

    // Main thread is Thread A
    object myLock = new Object();
    AutoResetEvent myEvent = new AutoResetEvent(false);
    ManualResetEvent completedEvent = new ManualResetEvent(false);
    
    ThreadPool.QueueUserWorkItem(s =>
    {
        for (int i = 0; i < 10000; i++)
        {
            lock (myLock)
            {
                // Do some work
            }
        }
        completedEvent.Set();
    });  // Thread B
    
    ThreadPool.QueueUserWorkItem(s =>
    {
        for (int i = 0; i < 10000; i++)
        {
            myEvent.WaitOne();
            lock (myLock)
            {
                // Do some work
            }
        }
    });  // Thread C
    
    // Main loop for thread A
    while (true)
    {
        lock (myLock)
        {
            // Do some work
            if (SomeSpecialCondition)
                break;
            else
                myEvent.Set();
        }
    }
    
    completedEvent.WaitOne(); // Wait for B to finish processing
    if (SomeSpecialCondition) // If we terminated without signaling C...
        myEvent.Set();        // Now allow thread C to clean up
    

    This essentially puts Thread A in charge of when Thread C gets to execute. Threads A and B will compete normally but it’s up to Thread A to signal the event for Thread C.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have multiple threads (C# application running on IIS) running that all need to
I have a Windows service that runs implementations of a framework across multiple threads.
I have multiple classes and threads that need to write to a Java Swing
I have a window form application, and it has multiple threads running that would
I have a method that is getting called from multiple threads. Each of the
I have a scenario where I have multiple threads adding to a queue and
I have a List object being accessed by multiple threads. There is mostly one
We have multiple MFC apps, which use CMutex( false, blah ), where blah allows
I have multiple classes that all derive from a base class, now some of
I have a std::map that I use to map values (field ID's) to a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.