avoid sending to closed channels

This commit is contained in:
David Zhao
2021-01-26 21:45:00 -08:00
parent a065a01592
commit ed0b9db655
12 changed files with 195 additions and 46 deletions
+63
View File
@@ -0,0 +1,63 @@
package utils
import (
"errors"
"sync/atomic"
)
var (
ErrChannelClosed = errors.New("cannot write to closed channel")
)
type AtomicFlag struct {
val uint32
}
// set flag to value if existing flag is different, otherwise return
func (b *AtomicFlag) TrySet(bVal bool) bool {
var v uint32
if bVal {
v = 1
}
old := b.val
// value is the same, nochanges
if old == v {
return false
}
return atomic.CompareAndSwapUint32(&b.val, old, v)
}
func (b *AtomicFlag) Get() bool {
return b.val == 1
}
// a channel that ignores writes when it closes instead of panic
type CalmChannel struct {
channel chan interface{}
isClosed AtomicFlag
}
func NewCalmChannel(size int) *CalmChannel {
return &CalmChannel{
channel: make(chan interface{}, size),
}
}
func (c *CalmChannel) Close() {
if !c.isClosed.TrySet(true) {
return
}
close(c.channel)
}
func (c *CalmChannel) ReadChan() <-chan interface{} {
return c.channel
}
func (c *CalmChannel) Write(o interface{}) error {
if c.isClosed.Get() {
return ErrChannelClosed
}
c.channel <- o
return nil
}
+46
View File
@@ -0,0 +1,46 @@
package utils
import (
"sync"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
)
func TestAtomicFlag(t *testing.T) {
t.Run("single thread, basic functionality", func(t *testing.T) {
f := AtomicFlag{}
assert.False(t, f.TrySet(false))
assert.False(t, f.Get())
assert.True(t, f.TrySet(true))
assert.True(t, f.Get())
})
t.Run("only one thread should succeed", func(t *testing.T) {
var numSets uint32
f := AtomicFlag{}
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
if f.TrySet(true) {
atomic.AddUint32(&numSets, 1)
}
wg.Done()
}()
}
wg.Wait()
assert.Equal(t, 1, int(numSets))
})
}
func TestCalmChannel(t *testing.T) {
t.Run("should receive nil after close", func(t *testing.T) {
c := NewCalmChannel(1)
c.Close()
assert.Equal(t, nil, <-c.ReadChan())
})
}