2022-02-28 15:32:19 -07:00
|
|
|
// run
|
2021-03-10 18:27:30 -07:00
|
|
|
|
|
|
|
// Copyright 2021 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import "sync"
|
|
|
|
|
2021-05-09 12:38:34 -06:00
|
|
|
// A Lockable is a value that may be safely simultaneously accessed
|
2021-03-10 18:27:30 -07:00
|
|
|
// from multiple goroutines via the Get and Set methods.
|
2021-05-09 12:38:34 -06:00
|
|
|
type Lockable[T any] struct {
|
2021-07-28 14:39:30 -06:00
|
|
|
x T
|
2021-03-10 18:27:30 -07:00
|
|
|
mu sync.Mutex
|
|
|
|
}
|
|
|
|
|
2021-05-09 12:38:34 -06:00
|
|
|
// Get returns the value stored in a Lockable.
|
|
|
|
func (l *Lockable[T]) get() T {
|
2021-03-10 18:27:30 -07:00
|
|
|
l.mu.Lock()
|
|
|
|
defer l.mu.Unlock()
|
2021-07-26 13:13:45 -06:00
|
|
|
return l.x
|
2021-03-10 18:27:30 -07:00
|
|
|
}
|
|
|
|
|
2021-05-09 12:38:34 -06:00
|
|
|
// set sets the value in a Lockable.
|
|
|
|
func (l *Lockable[T]) set(v T) {
|
2021-03-10 18:27:30 -07:00
|
|
|
l.mu.Lock()
|
|
|
|
defer l.mu.Unlock()
|
2021-07-26 13:13:45 -06:00
|
|
|
l.x = v
|
2021-03-10 18:27:30 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2021-07-26 13:13:45 -06:00
|
|
|
sl := Lockable[string]{x: "a"}
|
2021-03-10 18:27:30 -07:00
|
|
|
if got := sl.get(); got != "a" {
|
|
|
|
panic(got)
|
|
|
|
}
|
|
|
|
sl.set("b")
|
|
|
|
if got := sl.get(); got != "b" {
|
|
|
|
panic(got)
|
|
|
|
}
|
|
|
|
|
2021-07-26 13:13:45 -06:00
|
|
|
il := Lockable[int]{x: 1}
|
2021-03-10 18:27:30 -07:00
|
|
|
if got := il.get(); got != 1 {
|
|
|
|
panic(got)
|
|
|
|
}
|
|
|
|
il.set(2)
|
|
|
|
if got := il.get(); got != 2 {
|
|
|
|
panic(got)
|
|
|
|
}
|
|
|
|
}
|