How to wait until mutex unlocked?

There is an array of mutexes. My function:

  1. Checks is a mutex is locked

2a. If not, then locks it

2b. If locked, wait for unlocking and locks it

Another function unlocks it.

The problem is that I got crash in the waiting section:

HANDLE mutexes[N];

void func(int i)
  // (*) wait until unlocked or create if unlocked
  while ((mutexes[i] = CreateMutex(NULL, TRUE/*same with FALSE*/, NULL)) != NULL);
  /*or WaitForSingleObject(mutexes[i], INFINITE)*/

  mutexes[i] = CreateMutex(NULL, TRUE, NULL);

At (*) point i got crash - access violation. Crash occurs when it's trying to create mutexes[i] which is already have been created previously. I can't use WaitForSingleObject because at first time mutexes[i] isn't created and docs says WaitForSingleObject is undefined. Also if i use this function i get the same crash.

All i need is the analog of such simple pseudocode

if (mutex_has_been_created[mutexes[i]])

I tried to wrap it in a critical section and got same result. I'm sure that i is within correct range. I can't use Boost/pThreads/etc.

I know that my problem is quite easy, but i can't find the solution. In all examples i've seen a mutex is created before WaitForSingleObject, this doesn't work for me.

Thank you.


You really need to sort out the logic of your code: the creation of mutexes and the locking/unlocking are distinct operations and should be treated as such. Frankly, all this business of "trying to create mutexes which already have been created" does not make a whole lot of sense.


  1. CreateMutex initializes ("creates") the mutex.
  2. WaitForSingleObject et al lock the mutex (or time out).
  3. ReleaseMutex unlocks it.
  4. CloseHandle destroys it.

You create/destroy the mutex once and in between lock/unlock it as many times as you want.

When you try to lock a mutex that's already locked by someone else, your thread automatically blocks until the mutex becomes available.

Need Your Help

Getting started with Angular JS - Structure and other questions

javascript model-view-controller angularjs architecture

I'm new to AngularJS and have gone through its tutorial, read some of its documentation, and I understand the main aspects. But I'd like some help in organizing the structure of my project.

<sup> taking underline in chrome when given inside an element with text-decoration underline

html css border underline text-decorations

tried adjusting the sup tag with custom styling but it breaks when checked across the browsers. The current code shared in the fiddle works for firefox and IE ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.