From 0f035f34b46be55152ef430f9be66e1ce13eb680 Mon Sep 17 00:00:00 2001 From: Xe Iaso Date: Sun, 20 Aug 2023 09:58:46 -0400 Subject: cursed: add Mutex type Signed-off-by: Xe Iaso --- cursed/mutex.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 cursed/mutex.go (limited to 'cursed/mutex.go') diff --git a/cursed/mutex.go b/cursed/mutex.go new file mode 100644 index 0000000..82fe58f --- /dev/null +++ b/cursed/mutex.go @@ -0,0 +1,22 @@ +package cursed + +import "sync" + +// Mutex is a generic locking container for Go much like Rust's std::sync::Mutex. +// +// It differs from a normal sync.Mutex because it guards a value instead of just +// being something you lock and unlock to guard another value. When you are done with +// the value, call the function return to re-lock the mutex. +type Mutex[T any] struct { + val T + lock sync.Mutex +} + +func NewMutex[T any](val T) *Mutex[T] { + return &Mutex[T]{val: val} +} + +func (mu *Mutex[T]) Unlock() (T, func()) { + mu.lock.Lock() + return mu.val, func() { mu.lock.Unlock() } +} -- cgit v1.2.3