Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Locks and Mutexes in C# be used together

Tags:

c#

mutex

locking

Wouldn't this be overkill and only one of these necessary? I've searched and found different posts about Mutual Exclusion and locks in C# here and here.

Example:
In our app, we have a function that spins off multiple reconnection threads and inside this thread we use a Mutex and a lock. Wouldn't lock block access to this section of code and prevent connect from being updated by any other thread?

bool connect = false;
Mutex reconnectMutex = new Mutex(false, "Reconnect_" + key);

try
{
   lock(site)
   {
      if(site.ContainsKey(key))
      {
         siteInfo = (SiteInfo)site[key];
         if(reconnectMutex.WaitOne(100, true))
         {
            connect = true;
         }
      }
   }

   if (connect)
   { 
      // Process thread logic
   }
}
catch
{}

reconnectMutex.ReleaseMutex();

More Info:
This is in an ASP.NET WebService not running in a Web Garden.

like image 630
Jeremy Cron Avatar asked Mar 13 '09 15:03

Jeremy Cron


People also ask

Does C have mutex?

Does C have mutex? To have better control of resources and how threads access them, the GNU C Library implements a mutex object, which can help avoid race conditions and other concurrency issues. The term “mutex” refers to mutual exclusion.

What is mutex lock and unlock in C?

Mutexes are used to protect shared resources. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it.

How do mutexes work in C?

The idea behind mutexes is to only allow one thread access to a section of memory at any one time. If one thread locks the mutex, any other lock attempts will block until the first one unlocks. However, how is this implemented? To lock itself, the mutex has to set a bit somewhere that says that it is locked.

Is lock same as mutex?

A mutex is the same as a lock but it can be system wide (shared by multiple processes). A semaphore does the same as a mutex but allows x number of threads to enter, this can be used for example to limit the number of cpu, io or ram intensive tasks running at the same time.


2 Answers

That Mutex (because it has a name) will stop any process on the same machine accessing it as well, whereas lock will only stop other threads in the same process. I can't see from that code sample why you'd need both kinds of lock. It seems good practice to hold the simple lock for a short period of time - but then the much heavier interprocess mutex is locked for a probably longer (though overlapping) period! Would be simpler to just use the mutex. And perhaps to find out whether an interprocess lock is really necessary.

By the way, catch {} is absolutely the wrong thing to use in that scenario. You should use finally { /* release mutex */ }. They are very different. The catch will swallow far more kinds of exception than it should, and will also cause nested finally handlers to execute in response to low-level exceptions such as memory corruption, access violation, etc. So instead of:

try
{
    // something
}
catch
{}

// cleanup

You should have:

try
{
    // something
}
finally
{
    // cleanup
}

And if there are specific exceptions you can recover from, you could catch them:

try
{
    // something
}
catch (DatabaseConfigurationError x)
{
    // tell the user to configure the database properly
}
finally
{
    // cleanup
}
like image 109
Daniel Earwicker Avatar answered Sep 20 '22 14:09

Daniel Earwicker


"lock" is basically just a syntactic sugar for Montor.Enter/Exit. Mutex is a multi-process lock.

They have very different behavior. There is nothing wrong with using both in the same application or methods, since they're designed to block different things.

However, in your case, I think you may be better off looking into Semaphore and Monitor. It doesn't sound like you need to lock across processes, so they are probably a better choice in this situation.

like image 41
Reed Copsey Avatar answered Sep 21 '22 14:09

Reed Copsey