goext/syncext/atomic.go

114 lines
1.9 KiB
Go
Raw Permalink Normal View History

2022-11-30 23:35:47 +01:00
package syncext
2022-11-30 23:08:50 +01:00
2022-11-30 23:34:16 +01:00
import (
"context"
2023-01-29 22:28:08 +01:00
"gogs.mikescher.com/BlackForestBytes/goext/langext"
"sync"
2022-11-30 23:34:16 +01:00
"time"
)
2022-11-30 23:08:50 +01:00
type AtomicBool struct {
2023-01-29 22:28:08 +01:00
v bool
listener map[string]chan bool
lock sync.Mutex
2022-11-30 23:08:50 +01:00
}
func NewAtomicBool(value bool) *AtomicBool {
2023-01-29 22:28:08 +01:00
return &AtomicBool{
v: value,
listener: make(map[string]chan bool),
lock: sync.Mutex{},
2022-11-30 23:08:50 +01:00
}
}
func (a *AtomicBool) Get() bool {
2023-01-29 22:28:08 +01:00
a.lock.Lock()
defer a.lock.Unlock()
return a.v
2022-11-30 23:08:50 +01:00
}
func (a *AtomicBool) Set(value bool) bool {
2023-01-29 22:28:08 +01:00
a.lock.Lock()
defer a.lock.Unlock()
oldValue := a.v
2023-01-29 22:28:08 +01:00
a.v = value
for k, v := range a.listener {
select {
case v <- value:
// message sent
default:
// no receiver on channel
delete(a.listener, k)
}
2022-11-30 23:34:16 +01:00
}
return oldValue
2022-11-30 23:34:16 +01:00
}
func (a *AtomicBool) Wait(waitFor bool) {
2023-01-29 22:28:08 +01:00
_ = a.WaitWithContext(context.Background(), waitFor)
2022-11-30 23:34:16 +01:00
}
2022-11-30 23:38:42 +01:00
func (a *AtomicBool) WaitWithTimeout(timeout time.Duration, waitFor bool) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return a.WaitWithContext(ctx, waitFor)
}
2022-11-30 23:34:16 +01:00
func (a *AtomicBool) WaitWithContext(ctx context.Context, waitFor bool) error {
if err := ctx.Err(); err != nil {
return err
}
if a.Get() == waitFor {
return nil
}
2023-01-29 22:28:08 +01:00
uuid, _ := langext.NewHexUUID()
waitchan := make(chan bool)
a.lock.Lock()
a.listener[uuid] = waitchan
a.lock.Unlock()
defer func() {
a.lock.Lock()
delete(a.listener, uuid)
a.lock.Unlock()
}()
2022-11-30 23:34:16 +01:00
for {
if err := ctx.Err(); err != nil {
return err
}
2023-01-29 22:28:08 +01:00
timeOut := 1024 * time.Millisecond
2022-11-30 23:34:16 +01:00
if dl, ok := ctx.Deadline(); ok {
timeOutMax := dl.Sub(time.Now())
if timeOutMax <= 0 {
timeOut = 0
} else if 0 < timeOutMax && timeOutMax < timeOut {
timeOut = timeOutMax
}
}
2023-01-29 22:28:08 +01:00
if v, ok := ReadChannelWithTimeout(waitchan, timeOut); ok {
2022-11-30 23:34:16 +01:00
if v == waitFor {
return nil
}
} else {
if err := ctx.Err(); err != nil {
return err
}
if a.Get() == waitFor {
return nil
}
}
}
2022-11-30 23:08:50 +01:00
}