1
$\begingroup$
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?

$\endgroup$
  • 1
    $\begingroup$ Two producers -> race. $\endgroup$ – gnasher729 Mar 27 at 10:07
  • 1
    $\begingroup$ cpu can reorder updates of buffer[i] and in $\endgroup$ – Bulat Mar 27 at 11:38
  • $\begingroup$ @Bulat buffer[in modulo N]=msg in=in+1 are you saying CPU won't execute these lines of code in the same manner? $\endgroup$ – eddard.stark Mar 27 at 16:19
  • $\begingroup$ 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. $\endgroup$ – Bulat Mar 27 at 18:00
  • 1
    $\begingroup$ ...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. $\endgroup$ – Solomon Slow Mar 27 at 21:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.