userver: dist_lock::DistLockStrategyBase Class Reference
Loading...
Searching...
No Matches
dist_lock::DistLockStrategyBase Class Referenceabstract

#include <userver/dist_lock/dist_lock_strategy.hpp>

Detailed Description

Interface for distributed lock strategies.

Example

class MockDistLockStrategy final : public dist_lock::DistLockStrategyBase {
public:
~MockDistLockStrategy() override { EXPECT_FALSE(IsLocked()); }
void Acquire(std::chrono::milliseconds,
const std::string& locker_id) override {
UASSERT(!locker_id.empty());
attempts_++;
auto locked_by = locked_by_var_.Lock();
if (!locked_by->empty() && *locked_by != locker_id)
if (!allowed_) throw std::runtime_error("not allowed");
*locked_by = locker_id;
}
void Release(const std::string& locker_id) override {
auto locked_by = locked_by_var_.Lock();
if (*locked_by == locker_id) locked_by->clear();
}
bool IsLocked() {
auto locked_by = locked_by_var_.Lock();
return !locked_by->empty();
}
void Allow(bool allowed) { allowed_ = allowed; }
void SetLockedBy(const std::string& whom) {
auto locked_by = locked_by_var_.Lock();
*locked_by = whom;
}
size_t GetAttemptsCount() const { return attempts_; }
private:
std::atomic<bool> allowed_{false};
std::atomic<size_t> attempts_{0};
};

Definition at line 24 of file dist_lock_strategy.hpp.

+ Inheritance diagram for dist_lock::DistLockStrategyBase:

Public Member Functions

virtual void Acquire (std::chrono::milliseconds lock_ttl, const std::string &locker_id)=0
 
virtual void Release (const std::string &locker_id)=0
 

Member Function Documentation

◆ Acquire()

virtual void dist_lock::DistLockStrategyBase::Acquire ( std::chrono::milliseconds lock_ttl,
const std::string & locker_id )
pure virtual

Acquires the distributed lock.

Parameters
lock_ttlThe duration for which the lock must be held.
locker_idGlobally unique ID of the locking entity.
Exceptions
LockIsAcquiredByAnotherHostErrorwhen the lock is busy
anythingelse when the locking fails, strategy is responsible for cleanup, Release won't be invoked.

Implemented in storages::mongo::DistLockStrategy, and storages::postgres::DistLockStrategy.

◆ Release()

virtual void dist_lock::DistLockStrategyBase::Release ( const std::string & locker_id)
pure virtual

Releases the lock.

Parameters
locker_idGlobally unique ID of the locking entity, must be the same as in Acquire().
Note
Exceptions are ignored.

Implemented in storages::mongo::DistLockStrategy, and storages::postgres::DistLockStrategy.


The documentation for this class was generated from the following file: