First of all, what is Instruction Reordering? For example, you have written some C++ code and you have compiled it into machine instructions with gcc. However, the order in which instructions are actually executed may be different from the order you’ve written in C++. Probably due to optimization by compiler, CPU and memory system to fill pipeline, increase throughput, etc.
In the context of single-threading, this isn’t a problem, because in single-threading, reordering doesn’t break the data dependency among instructions. Through context switching, the dependency is guaranteed.
But this problem matters when it comes to multi-threading. In terms of “ordering”, we have
- the order defined in your C++ code
- the order after compilation (could be different from the source code)
- the order in which the CPU executes
- the order that other observes
The concurrency bug refers to the 4th order. Let’s explain this with an example
Concurrency: Example 1
1 | data = 42; |
1 | while (flag == 0) {} |
For this example, one execution order could be
- flag = 1 in Core 1
- Core 2 exits the loop
- Core 2 prints data
- data = 42 in Core 1
So you’ll find unexpected results due to concurrency.