Download presentation
Presentation is loading. Please wait.
1
ISP – 5 th Recitation Mutexes Code example
2
Mutex Wikipedia definition: Mutual exclusion (often abbreviated to mutex) algorithms are used in concurrent programming to avoid the simultaneous use of a common resource, such as a global variable, by pieces of computer code called critical sections.
3
What’s the idea? We have multiple threads/processes running all at the same (pseudo) time. Some of them want to access a common resource, say, print to the screen. In order to avoid creating a mess, we need to make sure that only one thread/process can access the resource for a specific piece of code.
4
Creating a Mutex Creating a new mutex Syntax : HANDLE CreateMutex( LPSECURITY_ATTRIBUTES MutexAttributes, BOOL InitialOwner, char* Name ); MutexAttributes can be set to NULL InitialOwner determines whether the thread calling CreateProcess would also be its first owner.
5
Creating a Mutex – Cont. Name field identifies the mutex in the system/process. Name is unique in the OS and can be used to gain access to a mutex that was opened by others. Unlike threadID/ProcessID, here we get to set it. If name already exists, a handle to the mutex is returned and GetLastError() shows ERROR_ALREADY_EXISTS. It’s possible to use NULL instead of the name but then we have to make sure we never lose the handle.
6
Opening an Existing Mutex Opening a mutex Syntax : HANDLE OpenMutex( DWORD DesiredAccess, BOOL InheritHandle, char* Name ); DesiredAccess requires a minimum permission of SYNCHRONIZE. InheritHandle allows processes, created by your program, to access the handle to the mutex
7
WaitForSingleObject() - Mutex WaitForSingleObject() is used for waiting for an object to become “signaled”. Syntax : DWORD WaitForSingleObject( HANDLE hObject, DWORD dwMilliseconds ); For mutexes, “Signaled” means that the mutex was released and is now owned by the thread that called for the wait function. Additional return values : WAIT_ABANDONED ( 80h) - the specified object is a mutex object that was not released by the thread that owned the mutex object before the owning thread terminated. Ownership of the mutex object is granted to the calling thread, and the mutex is set to nonsignaled.
8
ReleaseMutex() Releases ownership of the specified mutex object. Syntax : BOOL ReleaseMutex( HANDLE hMutex ); Returns 0 if failed, nonzero if successful NOTE : Not releasing a mutex might result in a deadlock. Recall dining phillosophers.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.