generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: concurrency issue in getDerivedPrimitive (#2480)
There is a situation where getDerivedPrimitive can be called concurrently, and two separate keys will be created. This fixes that issue. Also added a type-safe Mutex type.
- Loading branch information
1 parent
2a797e5
commit bc77ebb
Showing
2 changed files
with
41 additions
and
11 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
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,33 @@ | ||
package mutex | ||
|
||
import "sync" | ||
|
||
// Mutex is a simple mutex that can be used to protect a value. | ||
// | ||
// The zero value is safe to use if the zero value of T is safe to use. | ||
// | ||
// Example: | ||
// | ||
// var m mutex.Mutex[*string] | ||
// s := m.Lock() | ||
// defer m.Unlock() | ||
// *s = "hello" | ||
type Mutex[T any] struct { | ||
m sync.Mutex | ||
v T | ||
} | ||
|
||
func New[T any](v T) *Mutex[T] { | ||
return &Mutex[T]{v: v} | ||
} | ||
|
||
// Lock the Mutex and return its protected value. | ||
func (l *Mutex[T]) Lock() T { | ||
l.m.Lock() | ||
return l.v | ||
} | ||
|
||
// Unlock the Mutex. The value returned by Lock is no longer valid. | ||
func (l *Mutex[T]) Unlock() { | ||
l.m.Unlock() | ||
} |