Handling a mutex variable in a while loop check?

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.

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().

– Helium3 May 8 at 11:54 1 Most pthread functions return 0 if they succeed and some sort of error code if they fail. The assert is there in case something went wrong and you failed to acquire or release the mutex properly. – Brendan May 8 at 12:06.

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.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions