Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens to a mutex object if not released by parent applicaiton

I have a named mutex in my application.

 private Mutex TaskExitStatus = new Mutex(false, "TaskExit")

I acquire the mutex in a method using TaskExitStatus.WaitOne()

What will happen if I am not releasing the mutex while exiting the application? Will the mutex be disposed safely?

Update 1: Will both named and unnamed mutex behave the same when not released on application exit?

Update 2 This is what i read from MSDN link

Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The mutex object is destroyed when its last handle has been closed.

like image 463
Rockstart Avatar asked Oct 23 '12 10:10

Rockstart


People also ask

What happens when mutex is locked?

Mutexes are used to protect shared resources. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it.

Does disposing a mutex release it?

With a Mutex class, you call the WaitHandle. WaitOne method to lock and ReleaseMutex to unlock. Closing or disposing a Mutex automatically releases it.

Where are mutexes stored?

If the threads using a mutex in an application share memory, the handle of a mutex may be stored in the shared memory by the thread creating the mutex. When the other threads in an application require the handle to manipulate the mutex, it may be retrieved from the shared memory.

What is a mutex object and why is it used?

A mutex object is a synchronization object whose state is set to signaled when it is not owned by any thread, and nonsignaled when it is owned. Only one thread at a time can own a mutex object, whose name comes from the fact that it is useful in coordinating mutually exclusive access to a shared resource.


2 Answers

According to the documentation, it is abandoned (not necessarily disposed)

If a thread terminates while owning a mutex, the mutex is said to be abandoned

Also, heed the warning about abandoned Mutexes:

An abandoned mutex often indicates a serious error in the code. When a thread exits without releasing the mutex, the data structures protected by the mutex might not be in a consistent state. The next thread to request ownership of the mutex can handle this exception and proceed, if the integrity of the data structures can be verified.

like image 140
James Avatar answered Sep 22 '22 14:09

James


The purpose of a Mutex is to maintain a lock (for named Mutexes across applications) until it is released. If you do not release the Mutex the lock should be maintained on the resource until the computer is rebooted.

like image 22
Kevin Avatar answered Sep 26 '22 14:09

Kevin