From dc25bdab2f2d8ffbf06acbc6d4488e23f0632919 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Fri, 15 Apr 2022 15:56:06 +0800 Subject: [PATCH] feat: add Generate chan function in concurrency package --- concurrency/channel.go | 34 ++++++++++++++++++++++++++++++++++ concurrency/channel_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 concurrency/channel.go create mode 100644 concurrency/channel_test.go diff --git a/concurrency/channel.go b/concurrency/channel.go new file mode 100644 index 0000000..86cdf6e --- /dev/null +++ b/concurrency/channel.go @@ -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 +} diff --git a/concurrency/channel_test.go b/concurrency/channel_test.go new file mode 100644 index 0000000..c1d3396 --- /dev/null +++ b/concurrency/channel_test.go @@ -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) +}