1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add func in channel.go

This commit is contained in:
dudaodong
2022-04-19 16:03:12 +08:00
parent 980ff2c363
commit fc6dee9e77
2 changed files with 56 additions and 0 deletions

View File

@@ -124,3 +124,36 @@ func (c *Channel) FanIn(ctx context.Context, channels ...<-chan any) <-chan any
return multiplexedStream
}
// Or merge one or more done channels into one done channel, which is closed when any done channel is closed
func (c *Channel) Or(channels ...<-chan any) <-chan any {
switch len(channels) {
case 0:
return nil
case 1:
return channels[0]
}
orDone := make(chan any)
go func() {
defer close(orDone)
switch len(channels) {
case 2:
select {
case <-channels[0]:
case <-channels[1]:
}
default:
select {
case <-channels[0]:
case <-channels[1]:
case <-channels[2]:
case <-c.Or(append(channels[3:], orDone)...):
}
}
}()
return orDone
}

View File

@@ -3,6 +3,7 @@ package concurrency
import (
"context"
"testing"
"time"
"github.com/duke-git/lancet/v2/internal"
)
@@ -108,3 +109,25 @@ func TestFanIn(t *testing.T) {
assert.Equal(1, 1)
}
func TestOr(t *testing.T) {
assert := internal.NewAssert(t, "TestOr")
sig := func(after time.Duration) <-chan any {
c := make(chan interface{})
go func() {
defer close(c)
time.Sleep(after)
}()
return c
}
start := time.Now()
c := NewChannel()
<-c.Or(sig(2*time.Hour), sig(5*time.Minute), sig(1*time.Second), sig(1*time.Hour), sig(1*time.Minute))
t.Logf("done after %v", time.Since(start))
assert.Equal(1, 1)
}