Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ong/sync: add lockable type #487

Open
komuw opened this issue Dec 4, 2024 · 2 comments
Open

ong/sync: add lockable type #487

komuw opened this issue Dec 4, 2024 · 2 comments

Comments

@komuw
Copy link
Owner

komuw commented Dec 4, 2024

https://github.com/func25/go-practical-tips/blob/main/tips.md#making-a-type-with-built-in-locking-syncmutex-embedding

type Lockable[T any] struct {
    sync.Mutex
    Value T
}

func (l *Lockable[T]) SetValue(v T) {
    l.Lock()
    defer l.Unlock()

    l.Value = v
}

func (l *Lockable[T]) GetValue() T {
    l.Lock()
    defer l.Unlock()

    return l.Value
}
@komuw
Copy link
Owner Author

komuw commented Dec 6, 2024

package main

import (
	"fmt"
	"sync"
)

type Lockable[T any] struct {
	sync.Mutex
	value T
}

func (l *Lockable[T]) Do(f func(l *Lockable[T])) {
	l.Lock()
	defer l.Unlock()
	f(l)
}

var log = Lockable[int]{}

func main() { fmt.Println("Hello, 世界") }

@komuw
Copy link
Owner Author

komuw commented Dec 6, 2024

package main

import (
	"fmt"
	"sync"
	"time"
)

type Lockable[T any] struct {
	mu    sync.Mutex
	value T
}

// Do calls [f] and then returns the latest value in [Lockable] and any error from calling [f].
// Note: even where [f] returns an error the returned [value] may not be the zero value. It will be the latest value in [Lockable]
func (l *Lockable[T]) Do(
	f func(l *Lockable[T]) error,
) (value T, _ error) {
	l.mu.Lock()
	err := f(l)
	val := l.value // read only after calling f
	l.mu.Unlock()

	return val, err
}

func New[T any](value T) *Lockable[T] {
	return &Lockable[T]{value: value}
}

var log = New(0)

func main() {
	fmt.Println("val: ", log.value)
	val, err := log.Do(
		func(l *Lockable[int]) error {
			l.value = 34
			return nil
		},
	)
	if err != nil {
		panic(err)
	}
	fmt.Println("val: ", val)

	for i := range 19 {
		go func(ii int) {
			val, err := log.Do(
				func(l *Lockable[int]) error {
					l.value = ii
					return nil
				},
			)
			if err != nil {
				panic(err)
			}
			fmt.Println("ii: ", ii, "val: ", val)
		}(i)
	}

	time.Sleep(2 * time.Second)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant