Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling a mutex variable in a while loop check

Tags:

c

mutex

pthreads

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?

like image 393
some_id Avatar asked May 08 '11 11:05

some_id


3 Answers

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) {
    ...
}
like image 107
Ciaran McHale Avatar answered Oct 31 '22 14:10

Ciaran McHale


You should probably use a condition variable. See pthread_cond_wait(3) and pthread_cond_signal(3)

like image 23
ninjalj Avatar answered Oct 31 '22 15:10

ninjalj


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.

like image 28
Bo Persson Avatar answered Oct 31 '22 14:10

Bo Persson