Now will the code behave as expected or will we need to make ready volatile to get this to work?
I would advise to use the volatile
in the situation. Though in the case it seems it is not needed.
IOW, Personally I would have added volatile
and removed the locking: it is not needed for setting/reading the variable's value.
Will different compilers and libraries handle this differently?
I am hoping that there might be something round the mutex functions that will prevent optimization around itself or that the compiler generally does not optimize round function calls.
In your case the call to the function (pthread_mutex_lock()) has side effects and changes the execution environment. Thus compiler has to reread the global variable which might have being change by the call to the function.
To be really sure, you want to consult with C99's 5.1.2.3 Program execution
where from I have borrowed the terminology. To give you the taste:
[...] Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression may produce side effects. At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place. (A summary of the sequence points is given in annex C.)
In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object). [...]
Excerpt from the annex C:
The following are the sequence points described in 5.1.2.3:
— The call to a function, after the arguments have been evaluated (6.5.2.2).
And from there on.
In my experience, compilers are sufficiently smart nowadays and even when optimizing aggressively wouldn't do anything fancy with loop control variable which is a global variable.