Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutex and Event on Windows

Why do we need Mutex and Events in Windows? In the sense couldn't windows have just Mutex? What is that can be done with Events that cannot be done with Mutex?

like image 212
mihirg Avatar asked Sep 16 '10 14:09

mihirg


2 Answers

Events allows threads to block until some event (hence the name) is broadcast. Blocking on an Event means "Wake me when something happened"; you expect to be put to sleep. Event's are a signalling mechanism and provides support for this not found on mutexes, such as automatically being able to clear the signal as soon as someone who waited on it was woken up. Also, the API allows for blocking until one of or all of several events are signalled.

The mutex (Mutual Exclusion), on the other hand, is a scoped coordination mechanism for shared resources. Think transaction. You're not expecting to wait but want to access some shared resource, and only in the event that others are already accessing it, you're blocking.

If you tried to simulate an Event using a mutex, you'd face the problem that as soon as you acquired the lock (when should mean "event signalled"), you're keeping everybody else out until you release that lock. That is not the semantics of signalling an event; it may remain posted, and the "gates" would be open for every thread testing for the event, without acquiring any locks.

like image 54
Cumbayah Avatar answered Sep 20 '22 15:09

Cumbayah


Mutex dedicated for interprocess synchronization. This is kernel-mode object. Events for multithreaded synchronization within one process. This is user-mode object.

Mutex object is very general and to heavy, on the other hand Event object is much more light. In most of situations you must to use user-mode synchronization, because it supplies less CPU cycles.

like image 24
yozhik Avatar answered Sep 17 '22 15:09

yozhik