C++11多线程 —— 内存模型基础

1. 对象和内存位置

什么是对象?) The C++ Standard defines an object as “a region of storage” , some of these objects are simple values of a fundamental type such as int or float, whereas others are instances of user-defined classes.

内存位置)Whatever its type, an object is stored in one or more memory locations. Each such memory location is either an object (or subobject) of a scalar type such as unsigned short or my_class* or a sequence of adjacent bit fields. If you use bit fields, this is an important point to note: though adjacent bit fields are distinct objects, they’re still counted as the same memory location.


2. 对象、内存位置与并发

多个线程访问相同的内存位置时)If two threads access separate memory locations, there’s no problem: everything works fine. On the other hand, if two threads access the same memory location, then you have to be careful. If neither thread is updating the memory location, you’re fine; read-only data doesn’t need protection or synchronization. If either thread is modifying the data, there’s a potential for a race condition.

需要一个强制的顺序)In order to avoid the race condition, there has to be an enforced ordering between the accesses in the two threads. 两种方式:①使用锁;②使用原子操作。


3. 修改顺序

Every object in a C++ program has a defined modification order composed of all the writes to that object from all threads in the program, starting with the object’s initialization.

If different threads see distinct sequences of values for a single variable, you have a data race and undefined behavior. If you do use atomic operations, the compiler is responsible for ensuring that the necessary synchronization is in place.

Although all threads must agree on the modification orders of each individual object in a program, they don’t necessarily have to agree on the relative order of operations on separate objects.

猜你喜欢

转载自blog.csdn.net/fcku_88/article/details/88430890
今日推荐