views:

119

answers:

4

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 instance is destroyed

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

Is this OK?

Thank You

+4  A: 

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

John Gietzen
+1  A: 

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

DeadMG
+1  A: 

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.

Matthieu M.
+2  A: 

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.

MSalters