开发者

Is it safe to read global data from multiple threads?

开发者 https://www.devze.com 2023-01-02 16:58 出处:网络
The scenario is as follows: Create an instance of a class (std::map) and sore it as global variable. Spawn threads.

The scenario is as follows:

  1. Create an instance of a class (std::map) and sore it as global variable.
  2. Spawn threads.
  3. Threads read and use the same global instance of the class (call methods, access members etc)
  4. All spawned threads quit
  5. Global class ins开发者_如何学JAVAtance is destroyed

No mutex used, no spawn thread modifies the global class instance.

Is this OK?

Thank You


As long as you are never writing to that class, you should be safe.

However, as soon as you need to do reading or writing, you will need to use mutexes to protect both reading and writing.

You may want to look into the idea of a "shareable lock":

Boost has such a lock that allows for fast reads, but also includes the option to upgrade the lock to a "writer" if necessary. I think that this would probably be valuable for future-proofing.

http://www.boost.org/doc/libs/1_39_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_concepts.shared_lockable


Typically yes, but it's not a hard guarantee.

The core problem is that you need a memory barrier to make sure that the first thread writes back all data from registers to memory. However, it is very likely that this will happen when you create the second thread.


It is safe to read global data, as long as no thread is writing.


It is safe to read as long as it is guaranteed that the data is not mutated concurrently.

I would use a const qualification to ensure it though.

const std::map<Key,Value> global = ...;

Also, if you are not modifying the map afterward, you should take a peak at Loki::AssocVector: same interface, but faster for read-only usage.

0

精彩评论

暂无评论...
验证码 换一张
取 消