github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/consense/dpoa/Excute.go (about) 1 package dpoa 2 3 import ( 4 "fmt" 5 "sync" 6 "errors" 7 8 "github.com/sixexorg/magnetic-ring/log" 9 "github.com/sixexorg/magnetic-ring/consense/dpoa/comm" 10 ) 11 12 type actObj struct { 13 etype comm.ExcuteType 14 action func() 15 } 16 17 18 type SyncExec struct { 19 sync.RWMutex 20 execType map[comm.ExcuteType]struct{} 21 actions chan actObj 22 quit chan struct{} 23 } 24 25 func newExcutePool(no int) *SyncExec { 26 p := &SyncExec{ 27 actions: make(chan actObj), 28 execType: make(map[comm.ExcuteType]struct{}), 29 quit: make(chan struct{}), 30 } 31 32 for i := 0; i < no; i++ { 33 go p.loop(i, p.actions) 34 } 35 return p 36 } 37 38 func (p *SyncExec) loop(i int, actions <-chan actObj) { 39 defer log.Info("SyncExec loop stop", "i", i) 40 41 for { 42 select { 43 case actobj := <-actions: 44 //log.Info("SyncExec loop start", "i", i) 45 fmt.Println("SyncExec loop start", "i", i) 46 actobj.action() 47 p.Lock() 48 delete(p.execType, actobj.etype) 49 p.Unlock() 50 //log.Info("SyncExec loop stop", "i", i) 51 fmt.Println("SyncExec loop stop", "i", i) 52 case <-p.quit: 53 return 54 } 55 } 56 } 57 58 func (p *SyncExec) add(etype comm.ExcuteType, action func()) { 59 p.Lock() 60 defer p.Unlock() 61 if _, ok := p.execType[etype];ok{ 62 return 63 } 64 p.execType[etype] = struct{}{} 65 p.actions <- actObj{etype:etype, action:action} 66 } 67 68 func (p *SyncExec) close() { 69 close(p.quit) 70 } 71 72 func (self *ProcMode)Excute(etype comm.ExcuteType, action func()) error{ 73 if actPool, ok := self.excuteSet[etype]; ok{ 74 actPool.add(etype, action) 75 return nil 76 } 77 return errors.New(fmt.Sprintf("Server Excute ExcuteType err %v", etype)) 78 }