A semaphore is a counter. Acquiring it is only possible when the count is
non-zero. Acquiring causes the count to be decremented. If the count is
zero, attempting to acquire it blocks the thread.
A mutex allows exactly one thread to acquire it. It has a concept of
ownership to support recursive acquisition meaning that the owner can
continue to (re-acquire) the mutex without blocking. The owner, however,
must release the mutex as many times as it acquires it.
So, where a thread acquiring a semaphore repeatedly (in a nested way) will
exhaust the count in the semaphore, a thread acquiring a mutex (in a nested
way) would continue to do so without blocking until it hit the internal
limit of the nesting count (which likely causes an bugcheck but I don’t know
this is the case).
They are most definitely *not* interchangeable.
Sempahore: Often used with managed allocation of limited resource like a
pool of objects.
Mutex: Exclusive access to a single resource.
Good Luck,
Dave Cattley
-----Original Message-----
From: xxxxx@lists.osr.com
[mailto:xxxxx@lists.osr.com] On Behalf Of xxxxx@gmail.com
Sent: Monday, November 02, 2009 7:26 AM
To: Windows System Software Devs Interest List
Subject: [ntdev] mutex, semaphores: same or different ?
Till today I thought of mutex as a semaphore with limit = 2 but their
definitions inside wdm.h states some thing else.
A mutex or a mutent is defined as
typedef struct _KMUTANT {
DISPATCHER_HEADER Header;
LIST_ENTRY MutantListEntry;
struct _KTHREAD *OwnerThread;
BOOLEAN Abandoned;
UCHAR ApcDisable;
} KMUTANT, *PKMUTANT, *PRKMUTANT, KMUTEX, *PKMUTEX, *PRKMUTEX;
where as a semaphore definition is
typedef struct _KSEMAPHORE {
DISPATCHER_HEADER Header;
LONG Limit;
} KSEMAPHORE, *PKSEMAPHORE, *PRKSEMAPHORE;
So a there is some concept of thread ownership associated with a mutex which
is not with semaphore. Also msdn states that when a mutex is acquired
delivery of APCs will be disabled until it releases that mutex, this is also
not applied to semaphore.(At least the structure definition has nothing
which points to APC)
So what all other uses a mutex provide which a semaphore can not, in fact it
looks like that a semaphore is actually a event with limit.
Thanks
Aditya
NTDEV is sponsored by OSR
For our schedule of WDF, WDM, debugging and other seminars visit:
http://www.osr.com/seminars
To unsubscribe, visit the List Server section of OSR Online at
http://www.osronline.com/page.cfm?name=ListServer