Source file test/typeparam/lockable.go

     1  // run
     2  
     3  // Copyright 2021 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  package main
     8  
     9  import "sync"
    10  
    11  // A Lockable is a value that may be safely simultaneously accessed
    12  // from multiple goroutines via the Get and Set methods.
    13  type Lockable[T any] struct {
    14  	x  T
    15  	mu sync.Mutex
    16  }
    17  
    18  // Get returns the value stored in a Lockable.
    19  func (l *Lockable[T]) get() T {
    20  	l.mu.Lock()
    21  	defer l.mu.Unlock()
    22  	return l.x
    23  }
    24  
    25  // set sets the value in a Lockable.
    26  func (l *Lockable[T]) set(v T) {
    27  	l.mu.Lock()
    28  	defer l.mu.Unlock()
    29  	l.x = v
    30  }
    31  
    32  func main() {
    33  	sl := Lockable[string]{x: "a"}
    34  	if got := sl.get(); got != "a" {
    35  		panic(got)
    36  	}
    37  	sl.set("b")
    38  	if got := sl.get(); got != "b" {
    39  		panic(got)
    40  	}
    41  
    42  	il := Lockable[int]{x: 1}
    43  	if got := il.get(); got != 1 {
    44  		panic(got)
    45  	}
    46  	il.set(2)
    47  	if got := il.get(); got != 2 {
    48  		panic(got)
    49  	}
    50  }
    51  

View as plain text