Do condition variables still need a mutex if you're changing the checked value atomically?
Posted
by Joseph Garvin
on Stack Overflow
See other posts from Stack Overflow
or by Joseph Garvin
Published on 2010-03-27T23:41:10Z
Indexed on
2010/03/27
23:43 UTC
Read the original article
Hit count: 370
Here is the typical way to use a condition variable:
// The reader(s)
lock(some_mutex);
if(protected_by_mutex_var != desired_value)
some_condition.wait(some_mutex);
unlock(some_mutex);
// The writer
lock(some_mutex);
protected_by_mutex_var = desired_value;
unlock(some_mutex);
some_condition.notify_all();
But if protected_by_mutex_var is set atomically by say, a compare-and-swap instruction, does the mutex serve any purpose (other than that pthreads and other APIs require you to pass in a mutex)? Is it protecting state used to implement the condition? If not, is it safe then to do this?:
// The writer
protected_by_mutex_var = desired_value;
some_condition.notify_all();
With the writer never directly interacting with the reader's mutex? If so, is it even necessary that different readers use the same mutex?
© Stack Overflow or respective owner