Skip to content

Commit 1309ff8

Browse files
committed
Add shared_mutxt to protect data against current reading and writing
1 parent 0982970 commit 1309ff8

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

rest/service/MeterReadingService.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,25 @@
99

1010
#include <iostream>
1111
#include <map>
12-
#include <unordered_map>
12+
#include <mutex>
1313
#include <optional>
14+
#include <shared_mutex>
1415
#include <string>
16+
#include <unordered_map>
1517
#include <vector>
1618

1719
class MeterReadingService {
1820
public:
1921
std::optional<std::vector<ElectricityReading>> getReadings(const std::string &smartMeterId) {
22+
std::shared_lock<std::shared_mutex> lock(mtx);
2023
if (meterAssociatedReadings.find(smartMeterId) == meterAssociatedReadings.end()) {
2124
return {};
2225
}
2326
return meterAssociatedReadings[smartMeterId];
2427
}
2528

2629
void storeReadings(const std::string &smartMeterId, std::vector<ElectricityReading> &electricityReadings) {
30+
std::unique_lock<std::shared_mutex> lock(mtx);
2731
if (meterAssociatedReadings.find(smartMeterId) == meterAssociatedReadings.end()) {
2832
meterAssociatedReadings[smartMeterId] = {};
2933
}
@@ -36,6 +40,7 @@ class MeterReadingService {
3640

3741
private:
3842
std::unordered_map<std::string, std::vector<ElectricityReading>> &meterAssociatedReadings;
43+
mutable std::shared_mutex mtx;
3944
};
4045

4146
#endif // DEVELOPER_JOYOFENERGY_CPP_BEAST_METERREADINGSERVICE_H

0 commit comments

Comments
 (0)