Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the other threads that send back the signal when one thread calls WaitOne?

One of the things I'm having a hard time to understand in multi-threaded programming is that fact that when one thread reaches a line that calls WaitOne(), how do I know which other threads are involved? Where or how can I find (or understand) how the WaitHandle receives the signal? For example, I'm looking at this code right now:

private void RunSync(object state, ElapsedEventArgs elapsedEventArgs)
    {
        _mutex.WaitOne();
        using (var sync = GWSSync.BuildSynchronizer(_log))
        {
            try
            {
                sync.Syncronize();
            }
            catch(Exception ex)
            {
                _log.Write(string.Format("Error during synchronization : {0}", ex));
            }
        }
        _mutex.ReleaseMutex();
        _syncTimer.Interval = TimeBeforeNextSync().TotalMilliseconds;
        _syncTimer.Start();
    }

There are a few methods like this in the file (i.e RunThis(), RunThat()). These methods run inside a Windows service and are called when a Timer elapses. Each of these methods are called using different Timers and set up like this:

        //Synchro
        var timeBeforeFirstSync = TimeBeforeNextSync();
        _syncTimer = new System.Timers.Timer(timeBeforeFirstSync.TotalMilliseconds);
        _syncTimer.AutoReset = false;
        _syncTimer.Elapsed += RunSync;
        _syncTimer.Start();

I understand that when the Timer elapses, the RunSync method will run. But when it hits the WaitOne() line, the thread is blocked. But who is it waiting for? Which "other" thread will send the signal?

like image 971
Ray Avatar asked Nov 09 '22 06:11

Ray


1 Answers

WaitHandle is an abstraction, as stated in the documentation:

Encapsulates operating system–specific objects that wait for exclusive access to shared resources.

You don't know which other threads are involved, but you do know which other code is involved by checking the usage of the handle (_mutex in your case). Every WaitHandle derived class inherits WaitOne, but what happens after successful wait and how it's get signalled is specific. For instance, in your example _mutex most probably is a Mutex class, so WaitOne acts like "wait until it's free and take ownership" while the ReleaseMutex acts like "release ownership and signal". With that in mind, it should be obvious what all these methods do - ensuring that while RunThis you cannot RunThat and vise versa.

like image 53
Ivan Stoev Avatar answered Nov 15 '22 09:11

Ivan Stoev