tailscale/syncs/lock_example_test.go
Joe Tsai 2057205300 syncs: add LockFunc, LockValue, LockValues, and Mutex
The first 3 functions are helpers for running functions
under the protection of a lock.

The Mutex type is a wrapper over sync.Mutex with a Do method
that runs a function under the protection of a lock.

Updates #11038
Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
2024-07-13 14:40:04 -07:00

38 lines
762 B
Go

// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package syncs_test
import (
"encoding/hex"
"log"
"sync"
"tailscale.com/syncs"
)
func ExampleLockFunc() {
var nodesMu sync.Mutex
var nodes []string
syncs.LockFunc(&nodesMu, func() { nodes = append(nodes, "node123") })
}
func ExampleLockValue() {
var nodesMu sync.Mutex
var nodes []string
n := syncs.LockValue(&nodesMu, func() int { return len(nodes) })
log.Printf("there are %d nodes", n)
}
func ExampleLockValues() {
var bufferMu sync.Mutex
var buffer string
b, err := syncs.LockValues(&bufferMu, func() ([]byte, error) {
return hex.DecodeString(buffer)
})
if err != nil {
log.Fatalf("Decode error: %v", err)
}
log.Printf("decoded %d bytes", len(b))
}