[英]Multithreading: first access from another thread after being written… do I need volatile?
Hope the question is easy to understand. 希望这个问题易于理解。 In any case, let's write some code... 无论如何,让我们写一些代码...
struct MyClass
{
int a;
std::vector<char> b;
...
}
MyClass object;
Let's say I am running two threads A and B: 假设我正在运行两个线程A和B:
If the answer is yes, ie, that I need volatile in this case, I have another question: why is it thread safe to use immutable objects where data members are written in one thread and read in many others? 如果答案是肯定的,即在这种情况下我需要使用volatile,那么我还有另一个问题:为什么使用不可变对象在线程中写数据,而在多个线程中读取数据成员,这在线程上是安全的呢? It seems very similar to this case :) 似乎与这种情况非常相似:)
why is it thread safe to use immutable objects where data members are written in one thread and read in many others? 为什么使用不可变对象在线程中是安全的,因为数据成员是在一个线程中写入而在其他多个线程中读取的呢?
Immutable objects are created and then never change after that point. 创建不可变的对象,然后在那之后再也不会更改。 Since multithreaded access to an object is only possible after it is created (what is there to share before then) every thread will always see the same value. 由于仅在对象创建后(在此之前要共享什么),才可以对对象进行多线程访问,因此每个线程将始终看到相同的值。
So there is never a case where an immutable object will appear differently on separate threads, since there is no way for an immutable object can change state after it has been shared. 因此,永远不会有不可变对象在单独的线程上出现不同的情况,因为不可变对象共享后无法更改状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.