简体   繁体   中英

How to signal only one thread to wake up per event

What I want to do

I want to create some threads, say thread A, B, C, and block them until an event occurs. When an event occurs, I want to release only one thread.

For Example:

Before event occurs:
Thread A : blocked
Thread B : blocked
Thread C : blocked

After event occurs:
Thread A : blocked
Thread B : unblocked
THread C : blocked

I read that AutoResetEvent can do this but I can't specify which thread to be unlocked, and ManualResetEvent will unblock all the blocked threads.

Is there a way to achieve what I want to do?

Create multiple instances of ManualResetEvent , one for each Thread and use ManualResetEvent.WaitOne() in each Thread , eg

public void StartThreadA()
{
    _mreA = new ManualResetEvent();
    _threadA = new Thread(new ThreadStart(() => 
    {
        _mreA.WaitOne();
        // Continue
    });
}

When your even happens you can then handle it like so:

private void OnSomeEvent()
{
   _mreA.Set();
}

This is very limited in terms of scale, if you intend to use a large number of threads, I would suggest using a dictionary to look-up the ManualResetEvent for each thread.

Update

As I am now aware you are using a queue of threads I would do something like the following:

private Queue<ManualResetEvent> _queuedThreads = new Queue<ManualResetEvent>();

public void EnqueueThread()
{
    var mre = new ManualResetEvent();
    var thread = new Thread(new ThreadStart(() =>
    {
        mre.WaitOne();
        // Continue
    });

   _queuedThreads.Enqueue(mre);
}

private void OnEvent()
{
    var mre = _queuedThreads.Dequeue();
    mre.Set();   
}

You should consider using a Semaphore rather than a ManualResetEvent or AutoResetEvent.

There is a good basic example in the documentation here .

Also, here is a related stack overflow question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM