A race condition occurs in multithreading when more than one thread writes to memory (i.e., changes a variable) simultaneously. This results in undefined behaviour and we always want to avoid these.

How do we protect against race conditions? We should ensure that each thread doesn’t access shared memory at the same time.

  • One way we can do this is by vectorising everything when running parallel loops and keeping access to the specific iteration of the loop. By doing this, each thread accesses its own part of the vector and doesn’t interfere with others.
  • Make sure that nothing being written has a higher scope (i.e., should be local to the loop). If this is the case, the code should be refactored to avoid this.
  • We can use atomics to guarantee protection of variables.