Compare commits
2 Commits
Author | SHA1 | Date | |
---|---|---|---|
6a304b875a
|
|||
d12bf23b46
|
@@ -13,9 +13,9 @@ type AtomicBool struct {
|
|||||||
|
|
||||||
func NewAtomicBool(value bool) *AtomicBool {
|
func NewAtomicBool(value bool) *AtomicBool {
|
||||||
if value {
|
if value {
|
||||||
return &AtomicBool{v: 0, waiter: make(chan bool)}
|
|
||||||
} else {
|
|
||||||
return &AtomicBool{v: 1, waiter: make(chan bool)}
|
return &AtomicBool{v: 1, waiter: make(chan bool)}
|
||||||
|
} else {
|
||||||
|
return &AtomicBool{v: 0, waiter: make(chan bool)}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,14 +1,45 @@
|
|||||||
package syncext
|
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) {
|
func ReadChannelWithTimeout[T any](c chan T, timeout time.Duration) (T, bool) {
|
||||||
afterCh := time.After(timeout)
|
|
||||||
select {
|
select {
|
||||||
case rv := <-c:
|
case msg := <-c:
|
||||||
return rv, true
|
return msg, true
|
||||||
case <-afterCh:
|
case <-time.After(timeout):
|
||||||
return *new(T), false
|
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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user