Hi, I am learning multi-threaded programming (C++) using POSIX libraries.
I have been using the mutex's perfectly well yet I want to clarify something. In almost all examples that introduce mutex use the bathroom key metaphor, yet as I realized, it is possible for a function to access a variable with no problem if it does not bother to use/check the mutex created with the intention to protect it. Thus using the same metaphor the bathroom can be used even without the key. Then, a better metaphor should be defining mutex as a sign that signals whether one is using the bathroom or not (e.g. a red light), since if one does not bother to check the sign, he/she can still use it with the risk of finding someone using it already.
What do you think?
I'm not sure mutex variables can be accessed by any other function at any time. Unless the code wasn't done very well, no other threads can access a mutex variable while another is making use of it. Threads put a lock pthread_mutex_lock( &mutex1 ); on any mutex variables that are currently being accessed. So unless one doesn't do this, then it can be accessed at any time by any one. I guess your metaphor of the signals is better for defining when a thread does not check if the variable is in use, but that is bad programming procedures because you could inadvertently create an infinite loop where different threads are trying to accomplish different tasks with the same variable
I definitely agree that it is bad programming not to check a lock before using a variable you want to protect. My point was that if you made the mistake of not checking, even if the mutex is in lock state, you can access and change the variable. So the state of the mutex does not really lock the usage of the variable if you do not bother to check it. It is also obvious that the mutex that you create is just an object in itself. We do not somehow relate it with (like passing the addresses of) variables we want to protect. It just can be used as a signal whether one is using or not the variables created in the same scope.
Consider the following code:
using namespace std;
When you run it you will see that function 2 will access and change the counter even though the mutex created to (!) lock it, is in fact in a lock state (which function 1 never unlocks). So the mutex is not really a lock, unless you bother to use it. That is to say the compiler will not generate an error when one tries to access the variable without checking the state of the mutex.