How do you protect a common resource using mutexes?

Posted by Steve on Stack Overflow See other posts from Stack Overflow or by Steve
Published on 2010-03-18T15:15:28Z Indexed on 2010/03/18 15:41 UTC
Read the original article Hit count: 313

Filed under:
|

I have a common resource, which I want 1 and only 1 instance of my application (or it's COM API) to have access to at any time. I have tried to protect this resource using mutexes, but when multiple threads of a host dotnet application try to access the COM object, the mutex doesn't seem to be released. This is the code I have used to protect my resource.

repeat
  Mutex := CreateMutex(nil, True, PChar('Connections'));
until (Mutex <> 0) and (GetLastError <> ERROR_ALREADY_EXISTS);
  try
    //use resource here!
  finally
    CloseHandle(Mutex);
  end;

If I run the threads simultaneously, the first thread get's through (obviously, being the first one to create the mutex), but subsequent threads are caught in the repeat loop. If I run each thread at 5 second intervals, then all is ok.

I suspect I'm not using mutexes correctly here, but I have found very little documentation about how to do this.

Any ideas?

© Stack Overflow or respective owner

Related posts about delphi

Related posts about mutex