[Mono-dev] Mutex Bug

Edward Ned Harvey (mono) edward.harvey.mono at clevertrove.com
Wed Jul 2 19:31:57 UTC 2014


Before anything else ...  Can anybody recommend a way to do interprocess mutex?

I would like to confirm this is a bug before I go create a bug report in bugzilla.  Can anybody please confirm both (a) you get the same behavior, and (b) it's not correct behavior?

I want to make this observation as well:  The class in question is System.Threading.Mutex.  But on the mono class status pages, there seems to be no System.Threading.Mutex.  So that sounds a little suspicious to me, but maybe it's ok?  Or maybe I'm overlooking it somehow?

Here is some sample source code:
using System;
using System.Threading;

namespace FunWithMutex
{
    class MainClass
    {
        static string mutexName;
        const int numThreads = 5;
        static Thread[] allThreads = new Thread[numThreads];
        public static void Main(string[] args)
        {
            mutexName = @"Global\mutex-test-erihjbnkjvwiuehrnkjcxvjhwehiu";
            for (int i=0; i<numThreads; i++)
            {
                allThreads[i] = new Thread(new ThreadStart(DoSomething));
                allThreads[i].Name = "Thread #" + i.ToString();
                allThreads[i].Start();
            }
        }
        static void DoSomething()
        {
            System.Console.Error.WriteLine(Thread.CurrentThread.Name + " starting...");
            using (var myMutex = new Mutex(false,mutexName))
            {
                myMutex.WaitOne();
                try
                {
                    System.Console.Error.WriteLine(Thread.CurrentThread.Name + " running...");
                    Thread.Sleep(TimeSpan.FromSeconds(5));
                    System.Console.Error.WriteLine(Thread.CurrentThread.Name + " finished...");
                }
                finally
                {
                    myMutex.ReleaseMutex();
                }
            }
        }
    }
}


When run in windows .NET, you launch several processes that each run the above code, and the Mutex will only allow one process to enter at a time.  

When run in Mono, a single process obeys the mutex correctly, but multiple processes that are launched concurrently, each have an apparently private mutex, because each process will allow a single thread to enter the mutex concurrently.

In other words, the mutex *should* provide synchronization across multiple processes, but it doesn't.  Instead, it only provides synchronization across multiple threads within a single process.



More information about the Mono-devel-list mailing list