0

I have the following senario,

class enum class Status {
    Unknown, Pause, Normal, Resume
}

std::unordered_map<int, Status> status_map;

If at beginning I know all the key in status_map and initialze,

for(auto key:key_list) {
   status_map[key]=Status::Unknown;
}

Then later, thread1 will change known key's status, and thread2 will keep reading the status_map to make some decision, will this whole operation thread-safe?

tesla1060
  • 2,621
  • 6
  • 31
  • 43

1 Answers1

1

In a nutshell: no.

Imagine that your threads are executed on different cores, and each core has the map cached in it's own cache. Even worse: each core would cache part of the map. There is no guarantee that your reading thread would see consistent values that the writing thread is updating. You still need the values to be atomic:

std::unordered_map<int, std::atomic<Status>> status_map;

Without atomics the behavior is undefined. Using atomics you still can relax the memory model if you don't need full synchronization, but at least there would be some guarantees.

Dmitry Kuzminov
  • 6,180
  • 6
  • 18
  • 40