goext/syncext/channel.go

46 lines
809 B
Go
Raw Normal View History

2022-11-30 23:35:47 +01:00
package syncext
2022-11-30 23:34:16 +01:00
2022-11-30 23:52:19 +01:00
import (
"time"
)
// https://gobyexample.com/non-blocking-channel-operations
// https://gobyexample.com/timeouts
// https://groups.google.com/g/golang-nuts/c/Oth9CmJPoqo
2022-11-30 23:34:16 +01:00
func ReadChannelWithTimeout[T any](c chan T, timeout time.Duration) (T, bool) {
select {
2022-11-30 23:52:19 +01:00
case msg := <-c:
return msg, true
case <-time.After(timeout):
2022-11-30 23:34:16 +01:00
return *new(T), false
}
2022-11-30 23:52:19 +01:00
}
2022-11-30 23:34:16 +01:00
2022-11-30 23:52:19 +01:00
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
}
2022-11-30 23:34:16 +01:00
}