menu

perfbook-c3

3 Hardware and its Habits

atomic operations usually apply only to single elements of data.

原子操作存在其局限性,在数据结构复杂的场景下仍然需要内存屏障。

3.1.4 Memory Barriers

Memory barriers will be considered in more detail in Chapter 15 and Appendix C. In the meantime, consider the following simple lock-based critical section:

spin_lock(&mylock);
a = a + 1;
spin_unlock(&mylock);

If the CPU were not constrained to execute these statements in the order shown, the effect would be that the variable “a” would be incremented without the protection of “mylock”, which would certainly defeat the purpose of acquiring it.

To prevent such destructive reordering, locking primitives contain either explicit or implicit memory barriers.

Because the whole purpose of these memory barriers is to prevent reorderings that the CPU would otherwise undertake in order to increase performance, memory barriers almost always reduce performance, as depicted in Figure 3.6.