Thursday, September 17, 2015

Understanding Mutex entity

Studying example from MSDN article Using Mutex Objects some questions arise about mutex entity.
Here are experimentally proved suggestions:
  1. Mutexes are like files, open and create them with CreateMutex, close with CloseHandle (for files you use CreateFile, CloseHandle)
  2. Unnamed mutex is like critical section
  3. Mutexes are deleted after CloseHandle when no application currently have them opened
You can understand these things from running 10 simple programs which in short do the following:
HANDLE h
main(){
  h = CreateMutex("Global\\SuperMutex")
  CreateThread(WriteToDatabase)
  CloseHandle(h)
}

WriteToDatabase()
{
  WaitForSingleObject(h)
  ReleaseMutex(h)
}
Some programs create h = 0x3c, some h = 0x44
Some create mutex via CreateMutex while having ERROR_ALREADY_EXISTS

Pic 1. Running 10 of these programs:


Example sources are here...