Compare commits

...

4 Commits

Author SHA1 Message Date
6a304b875a v0.0.28 2022-11-30 23:52:19 +01:00
d12bf23b46 v0.0.27 2022-11-30 23:40:59 +01:00
52f7f6e690 v0.0.26 2022-11-30 23:38:42 +01:00
b1e3891256 v0.0.25 2022-11-30 23:35:47 +01:00
3 changed files with 48 additions and 11 deletions

View File

@@ -1,4 +1,4 @@
package dataext
package syncext
import (
"context"
@@ -13,9 +13,9 @@ type AtomicBool struct {
func NewAtomicBool(value bool) *AtomicBool {
if value {
return &AtomicBool{v: 0, waiter: make(chan bool)}
} else {
return &AtomicBool{v: 1, waiter: make(chan bool)}
} else {
return &AtomicBool{v: 0, waiter: make(chan bool)}
}
}
@@ -56,6 +56,12 @@ func (a *AtomicBool) Wait(waitFor bool) {
}
}
func (a *AtomicBool) WaitWithTimeout(timeout time.Duration, waitFor bool) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return a.WaitWithContext(ctx, waitFor)
}
func (a *AtomicBool) WaitWithContext(ctx context.Context, waitFor bool) error {
if err := ctx.Err(); err != nil {
return err

View File

@@ -1,14 +1,45 @@
package dataext
package syncext
import "time"
import (
"time"
)
// https://gobyexample.com/non-blocking-channel-operations
// https://gobyexample.com/timeouts
// https://groups.google.com/g/golang-nuts/c/Oth9CmJPoqo
func ReadChannelWithTimeout[T any](c chan T, timeout time.Duration) (T, bool) {
afterCh := time.After(timeout)
select {
case rv := <-c:
return rv, true
case <-afterCh:
case msg := <-c:
return msg, true
case <-time.After(timeout):
return *new(T), false
}
}
func WriteChannelWithTimeout[T any](c chan T, msg T, timeout time.Duration) bool {
select {
case c <- msg:
return true
case <-time.After(timeout):
return false
}
}
func ReadNonBlocking[T any](c chan T) (T, bool) {
select {
case msg := <-c:
return msg, true
default:
return *new(T), false
}
}
func WriteNonBlocking[T any](c chan T, msg T) bool {
select {
case c <- msg:
return true
default:
return false
}
}

View File

@@ -1,4 +1,4 @@
package dataext
package syncext
import (
"testing"