Jake
Jake

Reputation: 2907

CreateMutex Confusion

So I have called createmutex like so

  while(1){
    HANDLE h;
    h=CreateMutex(NULL,TRUE,"mutex1");
    y=WaitForSingleObject(h,INFINITE);
    ///random code
    ReleaseMutex(h)
   }

It runs fine after looping twice, but deadlocks on WaitForSingleObject (h,INFINITE) after the third loop. This is with two threads running concurrently. How can it deadlock when ReleaseMutex is called? Is the createmutex function called correctly?

Upvotes: 1

Views: 4931

Answers (2)

David Heffernan
David Heffernan

Reputation: 613302

I suspect you are trying to implement mutual exclusion within a single process. If that is so then the correct synchronization object is the critical section. The naming of these objects is a little confusing because both mutexes and critical sections peform mutual exclusion.

The interface for the critical section is much simpler to use, it being essentially an acquire function and a corresponding release function. If you are synchronizing within a single process, and you need a simple lock (rather than, say, a semaphore), you should use critical sections rather than mutexes.

In fact, very recently here on Stack Overflow, I wrote a more detailed answer to a question which described the standard usage pattern for critical sections. That post has lots of links to the pertinent sections of MSDN documentation.

You only need to use a mutex when you are performing cross process synchronization. Indeed you should only use a mutex when you are synchronizing across a process because critical sections perform so much better (i.e. faster).

Upvotes: 4

Ben Voigt
Ben Voigt

Reputation: 283733

You're waiting on a mutex that's already owned... please don't do that.

Also, you're not destroying the mutex, only releasing it. The next call should give you ERROR_ALREADY_EXISTS. The complete quote from MSDN is "If the mutex is a named mutex and the object existed before this function call, the return value is a handle to the existing object, GetLastError returns ERROR_ALREADY_EXISTS, bInitialOwner is ignored, and the calling thread is not granted ownership."

If any of the "random code" waits for the other thread to make progress, it could deadlock while owning the mutex. In which case the other thread will wait forever trying to acquire the mutex, which is the behavior you're seeing.

Upvotes: 5

Related Questions