Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Let a thread wait for n number of pulses

How can I wait for n number of pulses?

… // do something
waiter.WaitForNotifications();

I want the above thread to wait until being notified n times (by n different threads or n times by the same thread).

I believe there is a type of counter to do this, but I can't find it.

like image 776
Toto Avatar asked Aug 09 '13 09:08

Toto


2 Answers

Have a look at the CountdownEvent Class:

CountdownEvent Class

Represents a synchronization primitive that is signaled when its count reaches zero.

Example:

CountdownEvent waiter = new CountdownEvent(n);

// notifying thread
waiter.Signal();

// waiting thread
waiter.Wait();
like image 166
dtb Avatar answered Nov 15 '22 16:11

dtb


By using a simple ManualResetEvent and Interlocked.Decrement

class SimpleCountdown
{
    private readonly ManualResetEvent mre = new ManualResetEvent(false);

    private int remainingPulses;

    public int RemainingPulses
    {
        get
        {
            // Note that this value could be not "correct"
            // You would need to do a 
            // Thread.VolatileRead(ref this.remainingPulses);
            return this.remainingPulses;
        }
    }

    public SimpleCountdown(int pulses)
    {
        this.remainingPulses = pulses;
    }

    public void Wait()
    {
        this.mre.WaitOne();
    }

    public bool Pulse()
    {
        if (Interlocked.Decrement(ref this.remainingPulses) == 0)
        {
            mre.Set();
            return true;
        }

        return false;
    }
}

public static SimpleCountdown sc = new SimpleCountdown(10);

public static void Waiter()
{
    sc.Wait();
    Console.WriteLine("Finished waiting");
}

public static void Main()
{
    new Thread(Waiter).Start();

    while (true)
    {
        // Press 10 keys
        Console.ReadKey();

        sc.Pulse();
    }
}

Note that in the end, this your problem is often connected to this other problem: Workaround for the WaitHandle.WaitAll 64 handle limit?

My solution is good if you don't have .NET >= 4 (because the other solution, CountdownEvent, was introduced in .NET 4)

like image 43
xanatos Avatar answered Nov 15 '22 14:11

xanatos