Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are non-mutating operations inherently thread safe (C++)?

This is probably a dumb question, but consider the following psuedo-code:

struct Person {
    std::string name;
};

class Registry {
public:
  const std::string& name(int id) const {return _people[id].name;}
  void name(int id, const std::string& name) { [[scoped mutex]]; _people[id].name = name;}

private:
  std::map<int, Person> _people;
};

In this simple example, assume Registry is a singleton that will be accessed by multiple threads. I'm locking during an operation that mutates the data, but not during non-mutating access.

Is this thread safe, or should I also lock during the read operation? I'm preventing multiple threads from trying to modify the data at the same time, but I don't know what would happen if a thread was trying to read at the same time another was writing.

like image 584
amnesia Avatar asked Dec 08 '22 16:12

amnesia


1 Answers

If any thread can modify the data, then you need to lock for all access.

Otherwise, one of your "reading" threads could access the data when it is in an indeterminate state. Modifying a map, for example, requires manipulating several pointers. Your reading thread could acces the map while some - but not all - of the map has been adjusted.

If you can guarantee that the data is not being modified, multiple reads from multiple threads do not need to be locked, however that introduces a fragile scenario that you would have to keep a close eye on.

like image 121
Drew Dormann Avatar answered Dec 19 '22 18:12

Drew Dormann