From c410f08c2b0fad3aee0ba42c05bf4c0542d4a59d Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Mon, 16 Aug 2021 21:50:28 +0200 Subject: [PATCH] Kernel: Add ListedRefCounted template class This class implements the emerging "ref-counted object that participates in a lock-protected list that requires safe removal on unref()" pattern as a base class that can be inherited in place of RefCounted. --- Kernel/Library/ListedRefCounted.h | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Kernel/Library/ListedRefCounted.h diff --git a/Kernel/Library/ListedRefCounted.h b/Kernel/Library/ListedRefCounted.h new file mode 100644 index 0000000000..e0fdae1edc --- /dev/null +++ b/Kernel/Library/ListedRefCounted.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021, Andreas Kling + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include + +namespace Kernel { + +template +class ListedRefCounted : public RefCountedBase { +public: + bool unref() const + { + bool did_hit_zero = T::all_instances().with([&](auto& list) { + if (deref_base()) + return false; + list.remove(const_cast(static_cast(*this))); + return true; + }); + if (did_hit_zero) + delete const_cast(static_cast(this)); + return did_hit_zero; + } +}; + +}