Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:LMCache LMCache TTL Lock

From Leeroopedia


Knowledge Sources
Domains Concurrency, Storage Management
Last Updated 2026-02-09 00:00 GMT

Overview

Header file declaring the TTLLock class, a thread-safe counting lock with automatic time-to-live expiration.

Description

The TTLLock class provides a reentrant-style counting lock where each lock() call increments a counter and each unlock() call decrements it. The lock is considered held only when the counter is positive AND the TTL has not expired. All operations are implemented with lock-free atomic operations using std::atomic with sequential consistency ordering for mutations and acquire ordering for reads. The class uses std::chrono::steady_clock for monotonic time measurement.

Usage

Include this header in C++ storage manager code to protect cache entries with time-bounded locks. The TTL mechanism prevents deadlocks from clients that crash or disconnect without releasing the lock, making it suitable for distributed cache coordination scenarios.

Code Reference

Source Location

Signature

namespace lmcache {
namespace storage_manager {

class TTLLock {
 public:
  explicit TTLLock(uint32_t ttl_second = 300);
  void lock();
  void unlock();
  bool is_locked() const;
  void reset();

 private:
  static int64_t now_ms();
  static int64_t to_ms(const TimePoint& tp);

  std::atomic<int64_t> counter_;
  std::atomic<int64_t> expiration_ms_;
  const int64_t ttl_ms_;
};

}  // namespace storage_manager
}  // namespace lmcache

Import

#include "ttl_lock.h"

I/O Contract

Inputs

Name Type Required Description
ttl_second uint32_t No (default 300) TTL duration in seconds; the lock auto-expires after this period of inactivity

Outputs

Name Type Description
counter_ std::atomic<int64_t> Internal atomic counter tracking the number of active lock acquisitions
expiration_ms_ std::atomic<int64_t> Internal atomic timestamp (milliseconds since steady_clock epoch) of lock expiration
ttl_ms_ const int64_t Immutable TTL duration in milliseconds, computed from ttl_second at construction

Usage Examples

#include "ttl_lock.h"

using namespace lmcache::storage_manager;

// Default TTL of 300 seconds
TTLLock lock;

// Custom TTL of 10 seconds
TTLLock short_lock(10);

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment