-
Notifications
You must be signed in to change notification settings - Fork 20
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b9e73d9
commit 66e3385
Showing
2 changed files
with
94 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
79 changes: 79 additions & 0 deletions
79
data_tamer/include/data_tamer/details/locked_reference.hpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
#pragma once | ||
|
||
#include <memory> | ||
#include <mutex> | ||
|
||
namespace DataTamer | ||
{ | ||
/** | ||
* @brief The LockedRef class is used to share a pointer to an object | ||
* and a mutex that protects the read/write access to that object. | ||
* | ||
* As long as the object remains in scope, the mutex is locked, therefore | ||
* you must destroy this object as soon as the pointer was used. | ||
*/ | ||
template <typename T, class Mutex> | ||
class LockedRef { | ||
public: | ||
|
||
LockedRef() = default; | ||
|
||
LockedRef(T* obj, Mutex* obj_mutex): | ||
ref_(obj), mutex_(obj_mutex) { | ||
mutex_->lock(); | ||
} | ||
|
||
~LockedRef() { | ||
if(mutex_) { | ||
mutex_->unlock(); | ||
} | ||
} | ||
|
||
LockedRef(LockedRef const&) = delete; | ||
LockedRef& operator=(LockedRef const&) = delete; | ||
|
||
LockedRef(LockedRef && other) { | ||
std::swap(ref_, other.ref_); | ||
std::swap(mutex_, other.mutex_); | ||
} | ||
|
||
LockedRef& operator=(LockedRef&& other) { | ||
std::swap(ref_, other.ref_); | ||
std::swap(mutex_, other.mutex_); | ||
} | ||
|
||
operator bool() const { | ||
return ref_ != nullptr; | ||
} | ||
|
||
void lock() { | ||
if(mutex_) { | ||
mutex_->lock(); | ||
} | ||
} | ||
|
||
void unlock() { | ||
if(mutex_) { | ||
mutex_->unlock(); | ||
} | ||
} | ||
|
||
bool empty() const { | ||
return ref_ == nullptr; | ||
} | ||
|
||
const T& operator()() const{ | ||
return *ref_; | ||
} | ||
|
||
T& operator()() { | ||
return *ref_; | ||
} | ||
|
||
private: | ||
T* ref_ = nullptr; | ||
Mutex* mutex_ = nullptr; | ||
}; | ||
|
||
|
||
} |