Processing mutex variable while checking while loop

If a variable that changes in the stream and is correctly locked and unlocked using the mutex is read in the while loop in another thread, how to lock and unlock the mutex so that the while loop can read the value, is this even necessary?

I set a variable in a thread and test it in another thread using a while loop. How is a variable locked and unlocked to check the status of a while loop?

Is this the only sensible way to do this in order to have an extra variable that is used to start the while loop, and set that value to a variable that requires locking / unlocking?

+5
source share
3 answers

Edit : @ninjalj's suggestion to replace while-loop using a condition variable is good advice if you use while-loop to wait until the program state is reached. However, if you use while-loop to do the work until the program state is reached, then ...

You must 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, a utility function can 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 as follows:

while (valueOfSharedVariable() < 10) {
    ...
}
+5
source

, . . pthread_cond_wait(3) pthread_cond_signal(3)

+4

You should block it while reading, if there is even the slightest chance that someone else is writing at the same time. Otherwise, all kinds of things can happen, for example, you see a partial update or do not update at all.

If you use a value as a condition of the loop and are not exposed to updates during the loop, making a copy and unlocking it might be a good idea. If you are affected by the changes, you will need to save the castle, of course.

0
source

All Articles