github.com/awesome-flow/flow@v0.0.3-0.20190918184116-508d75d68a2c/pkg/corev1alpha1/actor/mux.go (about) 1 package actor 2 3 import ( 4 "sync" 5 6 core "github.com/awesome-flow/flow/pkg/corev1alpha1" 7 ) 8 9 type Mux struct { 10 name string 11 ctx *core.Context 12 queue chan *core.Message 13 wg sync.WaitGroup 14 } 15 16 var _ core.Actor = (*Mux)(nil) 17 18 func NewMux(name string, ctx *core.Context, params core.Params) (core.Actor, error) { 19 return &Mux{ 20 name: name, 21 ctx: ctx, 22 queue: make(chan *core.Message), 23 }, nil 24 } 25 26 func (m *Mux) Name() string { 27 return m.name 28 } 29 30 func (m *Mux) Start() error { 31 return nil 32 } 33 34 func (m *Mux) Stop() error { 35 close(m.queue) 36 m.wg.Wait() 37 return nil 38 } 39 40 func (m *Mux) Connect(nthreads int, peer core.Receiver) error { 41 for i := 0; i < nthreads; i++ { 42 m.wg.Add(1) 43 go func() { 44 for msg := range m.queue { 45 if err := peer.Receive(msg); err != nil { 46 msg.Complete(core.MsgStatusFailed) 47 m.ctx.Logger().Error(err.Error()) 48 } 49 } 50 m.wg.Done() 51 }() 52 } 53 return nil 54 } 55 56 func (m *Mux) Receive(msg *core.Message) error { 57 m.queue <- msg 58 return nil 59 }