| // run |
| |
| // Copyright 2020 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" |
| |
| // A Lockable is a value that may be safely simultaneously accessed |
| // from multiple goroutines via the Get and Set methods. |
| type Lockable[T any] struct { |
| T |
| mu sync.Mutex |
| } |
| |
| // Get returns the value stored in a Lockable. |
| func (l *Lockable[T]) Get() T { |
| l.mu.Lock() |
| defer l.mu.Unlock() |
| return l.T |
| } |
| |
| // Set sets the value in a Lockable. |
| func (l *Lockable[T]) Set(v T) { |
| l.mu.Lock() |
| defer l.mu.Unlock() |
| l.T = v |
| } |
| |
| func main() { |
| sl := Lockable[string]{T: "a"} |
| if got := sl.Get(); got != "a" { |
| panic(got) |
| } |
| sl.Set("b") |
| if got := sl.Get(); got != "b" { |
| panic(got) |
| } |
| |
| il := Lockable[int]{T: 1} |
| if got := il.Get(); got != 1 { |
| panic(got) |
| } |
| il.Set(2) |
| if got := il.Get(); got != 2 { |
| panic(got) |
| } |
| } |