[C++] Fixed race condition in MemoryLimitController
@@ -42,11 +42,16 @@ bool MemoryLimitController::tryReserveMemory(uint64_t size) {
}
void MemoryLimitController::reserveMemory(uint64_t size) {
- while (!tryReserveMemory(size)) {
+ if (!tryReserveMemory(size)) {
std::unique_lock<std::mutex> lock(mutex_);
+
+ // Check again, while holding the lock, to ensure we reserve attempt and the waiting for the condition
+ // are synchronized.
+ while (!tryReserveMemory(size)) {
condition_.wait(lock);
}
}
+}
void MemoryLimitController::releaseMemory(uint64_t size) {
uint64_t oldUsage = currentUsage_.fetch_sub(size);
