Mutex – synchronizing processes

Mutex is a mechanism which allows us to synchronize processes. (see also: semaphore).
Mutex is resource consuming stuff, so avoid it if possible.

Imagine we have an application which writes something into a file. If we run two instances lines in file will be mixed.

        public void WriteToSharedFileWithoutSync()
        {
            StreamWriter oFile = null;
            try
            {
                for (int i = 0; i <= 25; i++)
                {
                    oFile = File.AppendText(@"logger.log");
                    var txt = "Sample line..." + i;
                    oFile.WriteLine(txt);
                    Console.WriteLine(txt);
                    oFile.Flush();
                    oFile.Close();
                    Thread.Sleep(250);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                if (null != oFile)
                {
                    oFile.Close();
                    oFile.Dispose();
                }

                Console.Write("Saving finished.");
            }
        }

Run code above executing two separate instances of the same application to see results.

We can synchronize this two instances using mutex. See example below.

        private Mutex _mutex = new Mutex(false, "991FE2BE-A4DD-47CE-AC9B-C97A908EA560"); //create mutex with unique name somewhere in your application 


        public void WriteToSharedFileWithSync()
        {
            _mutex.WaitOne(); //wait if somebody else is in critical section

            StreamWriter oFile = null;
            try
            {
                for (int i = 0; i <= 25; i++)
                {
                    oFile = File.AppendText(@"logger.log");
                    var txt = "Sample line..." + i;
                    oFile.WriteLine(txt);
                    Console.WriteLine(txt);
                    oFile.Flush();
                    oFile.Close();
                    Thread.Sleep(250);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                if (null != oFile)
                {
                    oFile.Close();
                    oFile.Dispose();
                }

                _mutex.ReleaseMutex(); //release critical section after writing
                Console.Write("Saving finished.");
            }
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s