I've implemented a systemd service in C++ that automatically starts when the system boots. The goal of this service is to acquire system resources and make them accessible via an API.
One of these resources is the cpu load. I've implemented a separate thread that reads the information from '/proc/stat' in a set interval (each second) and simultaneously calculates the cpu load from these readings. The readings are stored in an std::unordered_map<std::string, uint32_t> and the values are read from the main program whenever the API is called.
I've read that I should use a read/write lock when writing and reading from the same container in different threads. Is this assumption correct?
How would I implement such a read/write lock?
The values of the map are directly written by specifying the key:
my_map['some_key'] = value
What would happen if i lock the container with a read lock and the separate thread tries to write simultaneously? Since new values are written each second, that might be problematic.
This is not the only option but this is a good choice in this case. A basic lock can work but it will be slower (it will serialise reads here while reads needs to be fast and this is not a problem if writes are slow in your case).
In C++17, there is a
shared_mutexclass implementing such a mechanism. Thesharedaccess mode is for the readers and theexclusiveaccess mode is for the writers.If the thread writing in the container do not lock a write lock of the read-write mutex, then there is a race condition causing an undefined behaviour (eg. crash). With a read-write lock, the writes to the container will be mutually exclusive (ie. safe). The same ting happens between the reads and writes but not between multiple reads.