Multiple threads writing to the same variable at the same time lead to data races, which can cause random behaviour depending on, which threads is faster, or corrupt your data. To prevent these race conditions we need to lock all outer threads out while one is writing to a shared variable.

Knowledge

One way of dealing with race conditions are critical sections. Only one thread is allowed in the same critical sections. The others have to wait until the critical section is free again. Then the next thread can claim the critical section. You could solve this particular problem more elegantly and we will come back to that, but for now just use critical sections.

To mark a block as a critical section, use the compiler directive pragma omp critical.

Task

Resolve the race condition with a critical section.