<div dir="ltr"><br><div class="gmail_extra">2014-05-29 20:07 GMT+02:00 Jonathan Thambidurai <span dir="ltr"><<a href="mailto:jonathan@fastly.com" target="_blank">jonathan@fastly.com</a>></span>:<br><div class="gmail_quote">

<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div dir="ltr">Hi Remi,<div><br></div><div>Volatile (threading is irrelevant here) will stop a given (eg "chunk->next") from being stored in a register for future accesses.</div>

<div><br></div><div>Thus, let us look at the following simple case (though this is not precisely the code),</div>
<div><br></div><div>while(chunk->next);</div><div><br></div><div>A compiler can reasonably look at the above, decide that chunk->next cannot change, stash it in a register and thus infinitely loop if it is not null.  Lets call this execution flow thread 1.</div>


<div><br></div><div>Let us assume that a second thread t2 changes chunk->next.  Since t1 is storing what it believes to be chunk->next in a register (and not updating it from the actual memory location), t1 will get stuck in whatever state it was in in the first place.</div>


<div><br></div><div>I only added the volatile after I ran into exactly the aforementioned phenomenon.</div><div><br></div><div>Please tell me what you disagree with above.</div><span class="HOEnZb"><font color="#888888"><div>

<br></div><div>--Jonathan</div><div><br></div></font></span></div></blockquote><div>But accessing volatile storage does not create a memory barrier so it might be reordered with non-volatile accesses. Also, it's not necessarily atomic. So this is generally a bad idea.<br>

<br></div><div>You should use atomic variables or a synchronization primitive.<br></div><div> </div></div>-- <br>Félix Abecassis<div><a href="http://felix.abecassis.me" target="_blank">http://felix.abecassis.me</a></div>

</div></div>