Search This Blog

Tuesday, May 31, 2005

(Fast) Mutexes - Description

Our atomic functions work beautifully for performing thread-safe access to a single integer variable. But what if we have a more complex data type, such as a string, or a linked list? Similarly, what if we have more than one variable which must be updated at the same time (where updating one but not the other would cause bad things to happen)? This is what a mutex is for.

A mutex is used to protect access to one or more variable across multiple threads. Threads enter the mutex before accessing the variables, and leave the mutex when they're done. If, while one thread is inside the mutex, a second thread tries to enter the mutex, the second thread will get in line and go into wait until the first thread leaves the mutex. Thus, a mutex ensures MUTually EXclusive access to shared variables.

It is worth noting that only variables which are shared across threads need protection from concurrent access. Variables which are only used by a single thread do not need protection, be it by atomic variables or a mutex. Both atomic variables and use of a mutex are slower than thread-unsafe access, and so are not desirable where not needed.

No comments: