First of all, I have a gut feeling that says, inside an if statement, if I am using the variable, it counts as reading the variable so I should lock it with mutex there also (if another pthread might be doing stuff with it). Am I right that I should lock it?
The example situation in simplified manner is given below.
in one thread I am using the below statement:
if(event){
// Should I or should I not lock event here to use it
// inside if statement?
pthread_mutex_lock(&mutex_event);
event = 0;
pthread_mutex_unlock(&mutex_event);
// blah blah code here
// blah blah code here
// blah blah code here
}
in another thread I am doing
pthread_mutex_lock(&mutex_event);
event = 1;
pthread_mutex_unlock(&mutex_event);
Second question, if I do need to lock it, how should I do it in a classy programmers manner? In other words, what is the general convention. I don't like the below idea as I have to wait for all of the lines inside "if" to execute to be able to unlock mutex again.
pthread_mutex_lock(&mutex_event);
if(event){
event = 0;
// blah blah code here
// blah blah code here
// blah blah code here
}
pthread_mutex_unlock(&mutex_event);
I am ok with this idea, but probably it could look prettier:
pthread_mutex_lock(&mutex_event);
if(event){
event = 0;
pthread_mutex_unlock(&mutex_event);
// blah blah code here
// blah blah code here
// blah blah code here
}
else
{
pthread_mutex_unlock(&mutex_event);
}
I find that it gets trickier with a while loop and this is the primitive solution I have got:
pthread_mutex_lock(&mutex_event);
store_event = event; // store_event is local
pthread_mutex_unlock(&mutex_event);
while(store_event){
// blah blah code here
// blah blah code here
// blah blah code here
}