Let's suppose the following C code snippet:
static bool var;
DECLARE_MUTEX(lock);
void mod_set_var(bool v)
{
mutex_lock(lock);
var = v;
mutex_unlock(lock);
}
bool mod_get_var(void)
{
return var;
}
Let's suppose that the above functions can be accessed by many different threads, and that we don't want to rely at all in the ability of the underneath arch. to do atomic assignments and the like
As far as I understand, the theory says that mod_get_var
should be protected with a mutex. However, I can't imagine the case in which the above code may cause a problem.
I have read this other post in which @David Schwartz exposes an example of disaster. However, that happens if foo j;
is created locally inside a function, but here var
is a statically allocated variable. I'm not sure if the mentioned example applies to the case above. If it does, I don't see how.
How can the code above end up in undesired/unexpected behavior?