github.com/searKing/golang/go@v1.2.117/go/generator/generator.runtime.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package generator 6 7 import "context" 8 9 // runtimeGenerator is an implement of Generator's behavior actually. 10 type runtimeGenerator struct { 11 // fired func, as callback when supplierC is consumed successfully 12 // arg for msg receiver 13 // msg for msg to be delivered 14 f func(ctx context.Context, arg any, msg any) 15 arg any 16 17 ctx context.Context 18 cancel context.CancelFunc 19 20 // data src 21 supplierC <-chan any 22 // data dst 23 consumerC chan any 24 25 // guard channels below 26 } 27 28 func (g *runtimeGenerator) start() { 29 go func() { 30 for { 31 select { 32 case <-g.ctx.Done(): 33 return 34 case s, ok := <-g.supplierC: 35 if !ok { 36 close(g.consumerC) 37 g.stop() 38 return 39 } 40 g.f(g.ctx, g.arg, s) 41 } 42 } 43 }() 44 } 45 46 func (g *runtimeGenerator) stop() bool { 47 select { 48 case <-g.ctx.Done(): 49 return false 50 default: 51 g.cancel() 52 return true 53 } 54 } 55 56 func (g *runtimeGenerator) stopped() bool { 57 select { 58 case <-g.ctx.Done(): 59 return true 60 default: 61 return false 62 } 63 }