If a variable that is being modified in a thread and is properly locked and unlocked using a mutex is read in a while loop in another thread how does one lock and unlock the mutex so that the while loop can read the value, is it even necessary?
I set a variable in a thread and check it in another thread using a while loop. How is the variable locked and unlocked for checking in the while loop condition?
Is the only reasonable way to do it, to have an additional variable that is used to run the while loop and set that to the value of the variable that needs locking/unlocking?
Edit: @ninjalj's suggestion to replace the while
-loop with use of a condition variable is good advice if you are using the while
-loop to wait until a program state has been reached. However, if you are using a while
-loop to do work until a program state has been reached then...
You should wrap the "lock-mutex; examine variable; unlock mutex
" code in a utility function, and your while
-loop condition can then call that function. For example, the utility function might be written as shown in the following code:
int valueOfSharedVariable()
{
int status;
int result;
status = pthread_mutex_lock(&mutex);
assert(status == 0);
result = sharedVariable;
status = pthread_mutex_unlock(&mutex);
assert(status == 0);
return result;
}
Then, your while
-loop condition can be written like the following:
while (valueOfSharedVariable() < 10) {
...
}
You should probably use a condition variable. See pthread_cond_wait(3)
and pthread_cond_signal(3)
You must lock it during the read, if there is the slightest chance someone else is writing at the same time. Otherwise all kinds of things could happen, like you seeing a partial update or no update at all.
If you use the value as a loop condition, and are not affected by updates during the loop, making a copy and release the lock could be a good idea. If you would be affected by a change, you will have to keep the lock of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With