# Is there any race condition in this code

Message buffer[N]
Int in=0, out=0

send(message msg)
while in-out==N do nothing
buffer[in modulo N]=msg
in=in+1
return

message recieve()
while in == out do nothing
msg = buffer[out modulo N]
out=out+1
return msg


This is a code for a producer consumer problem. The producer produces a message and with the send function saves it into the buffer. The consumer receives that message from the buffer. The buffer, in and out are global variables. Where is the race condition here? I can't find any?

• Two producers -> race. – gnasher729 Mar 27 at 10:07
• cpu can reorder updates of buffer[i] and in – Bulat Mar 27 at 11:38
• @Bulat buffer[in modulo N]=msg in=in+1 are you saying CPU won't execute these lines of code in the same manner? – eddard.stark Mar 27 at 16:19
• en.wikipedia.org/wiki/Memory_model_(programming) : The memory model stipulates that changes to the values of shared variables only need to be made visible to other threads when such a synchronization barrier is reached. Moreover, the entire notion of a race condition is defined over the order of operations with respect to these memory barriers. – Bulat Mar 27 at 18:00
• ...and the reason why the memory model of most programming languages is so relaxed during the spaces between memory barriers is that it allows a substantially more efficient implementation of all of the cases where threads access variables that are not shared. Multiprocessor systems would not be worth building if every update had to be visible to every other thread in the order in which the updates happened. – Solomon Slow Mar 27 at 21:48