mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-11 16:22:26 +08:00
feat: add Generate chan function in concurrency package
This commit is contained in:
34
concurrency/channel.go
Normal file
34
concurrency/channel.go
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
// Copyright 2021 dudaodong@gmail.com. All rights reserved.
|
||||||
|
// Use of this source code is governed by MIT license
|
||||||
|
|
||||||
|
// Package concurrency contain some functions to support concurrent programming. eg, goroutine, channel, async.
|
||||||
|
package concurrency
|
||||||
|
|
||||||
|
// Channel is a logic object which implemented by go chan
|
||||||
|
// all methods of channel are in the book tiled《Concurrency in Go》
|
||||||
|
type Channel struct {
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewChannel return a Channel instance
|
||||||
|
func NewChannel() *Channel {
|
||||||
|
return &Channel{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate a data of type any chan
|
||||||
|
func (c *Channel) Generate(done <-chan any, datas ...any) <-chan any {
|
||||||
|
dataStream := make(chan any)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
defer close(dataStream)
|
||||||
|
|
||||||
|
for _, v := range datas {
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
return
|
||||||
|
case dataStream <- v:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return dataStream
|
||||||
|
}
|
||||||
24
concurrency/channel_test.go
Normal file
24
concurrency/channel_test.go
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
package concurrency
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/duke-git/lancet/v2/internal"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGenerate(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestToChar")
|
||||||
|
|
||||||
|
done := make(chan any)
|
||||||
|
defer close(done)
|
||||||
|
|
||||||
|
c := NewChannel()
|
||||||
|
intStream := c.Generate(done, 1, 2, 3)
|
||||||
|
|
||||||
|
// for v := range intStream {
|
||||||
|
// t.Log(v)
|
||||||
|
// }
|
||||||
|
assert.Equal(1, <-intStream)
|
||||||
|
assert.Equal(2, <-intStream)
|
||||||
|
assert.Equal(3, <-intStream)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user