Search code examples
c#.netmutexpass-by-referencereference-type

Are Mutex objects passed by reference?


I am constructing several objects from a Class and using a particular function from these classes to start Threads. Now the Class containing the member function from where these objects are constructed, has a static private Mutex member. I am passing this static member to the constructors and inside each constructor, the passed Mutex(presumably by reference) is assigned to another local member.

If I then use each of these local Mutex member to ensure Thread safety, will I be able to achieve this? I am counting on the fact, no matter how many different instances of the object containing the Thread function exists, since they are all referring to the same Mutex object, Thread safety is ensure if properly used.

Please find below code snippet to represent the Idea:

Class ThreadClass
{
 private Mutex myCopyOfMutex;
public ThreadClass(Mutex _globalMutex)
{
 myCopyOfMutex = _globalMutex;
}
public ThreadFunction()
{

// Wait until it is safe to enter.
myCopyOfMutex.WaitOne();
// critical code

// Release the Mutex.
 myCopyOfMutex.ReleaseMutex();

}
}

Class MotherClass
{
  private static Mutex mut = new Mutex();

  ThreadClass one = new ThreadClass(mut); // first instance
  Threadclass two = new ThreadClass(mut); // second instance

// Assign the Thread function to run on separate Thread

}

Solution

  • Yes, it will work. No, it's not passed by reference.

    There is an important difference between passing a reference and passing by reference.

    When you pass a reference type to a method, it's normally passed as a reference:

    SomeMethod(mutex);
    

    To pass a parameter by reference, you use the ref keyword:

    SomeMethod(ref mutex);
    

    The parameter in the method signature also has to be declared using the ref keyword:

    public void SomeMethod(ref Mutex mutex) {
    

    Passing a variable by reference means that you pass a reference to the variable, not a copy of the reference that is contained in the variable. The method can then change the variable itself, not only the object that the reference points to.

    In most cases, and also in this case, you should pass parameters in the regular way. Passing by reference is only done when you need it for a specific reason.