简体   繁体   English

多线程:写入后首先从另一个线程进行访问...我需要使用volatile吗?

[英]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:

  1. Thread A creates object and reads or writes some data members except a and b. 线程A创建对象并读取或写入除a和b之外的一些数据成员。
  2. Thread A passes a pointer to object to a function that will run in thread B. 线程A将指向对象的指针传递给将在线程B中运行的函数。
  3. Thread B writes a or adds data to vector b. 线程B向向量b写a或将数据添加到向量b。
  4. Thread A reads a and b (ie, access these for the first time). 线程A读取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.

相关问题 在被另一个线程写入并在该线程加入之后从主线程访问变量是否安全? - Is it safe to access a variable from the main thread after it was written to by another thread and after that thread was joined? 我是否需要保护一个线程写入并被多个线程读取的变量? - Do I need to guard a variable that is written by one thread and read by many? 我是否需要在多线程环境中保护对STL容器的读访问权限? - Do I need to protect read access to an STL container in a multithreading environment? 我是否需要同步对int的线程访问? - Do I need to synchronize thread access to an int? 易失性和多线程:以下线程安全吗? - Volatile and multithreading: is the following thread-safe? 为了线程安全,我们是否需要volatile关键字和互斥锁一起锁定? - Do we need volatile keyword and the mutex locks together for thread safety? 多线程处理树数据结构的只读功能。我需要什么来使线程安全 - Multithreading a read-only function of a tree data structure.. What do i need to make thread safe 多线程。 我是否需要关键部分来进行只读访问? - Multithreading. Do I need critical sections for read-only access? 多线程-线程接一个线程(立即) - Multithreading - thread after thread (immediately) 嵌入式C ++ 11代码 - 我需要volatile吗? - Embedded C++11 code — do I need volatile?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM