Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify nano::locked to work in const contexts #4846

Merged
merged 1 commit into from
Feb 19, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion nano/lib/locks.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -299,11 +299,47 @@ class locked
locked * owner{ nullptr };
};

struct const_scoped_lock final
{
const_scoped_lock (locked const * owner_a) :
owner (owner_a)
{
owner->mutex.lock ();
}

~const_scoped_lock ()
{
owner->mutex.unlock ();
}

T const * operator->() const
{
return &owner->obj;
}

T const & get () const
{
return owner->obj;
}

T const & operator* () const
{
return get ();
}

locked const * owner{ nullptr };
};

scoped_lock operator->()
{
return scoped_lock (this);
}

const_scoped_lock operator->() const
{
return const_scoped_lock (this);
}

T & operator= (T const & other)
{
nano::unique_lock<nano::mutex> lk (mutex);
Expand All @@ -313,6 +349,7 @@ class locked

operator T () const
{
nano::unique_lock<nano::mutex> lk (mutex);
return obj;
}

Expand All @@ -322,8 +359,14 @@ class locked
return scoped_lock (this);
}

/** Returns a const scoped lock wrapper, allowing multiple calls to the underlying object under the same lock */
const_scoped_lock lock () const
{
return const_scoped_lock (this);
}

private:
T obj;
nano::mutex mutex;
mutable nano::mutex mutex; // Mutex needs to be mutable to allow locking in const methods
};
}
Loading