From 6125fc9d836e0eb25bc18a6291221267fbb1f98f Mon Sep 17 00:00:00 2001 From: Paladz Date: Mon, 2 Apr 2018 14:06:34 +0800 Subject: [PATCH] init version for make submit work handle asyn case (#511) * init version for make submit work handle asyn case * edit for golint and test * change the channel size due to code review --- mining/miningpool/minepool.go | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/mining/miningpool/minepool.go b/mining/miningpool/minepool.go index 9df2b86b..2f23c5dc 100644 --- a/mining/miningpool/minepool.go +++ b/mining/miningpool/minepool.go @@ -14,12 +14,21 @@ import ( "github.com/bytom/protocol/bc/types" ) -const blockUpdateMS = 1000 +const ( + blockUpdateMS = 1000 + maxSubmitChSize = 50 +) + +type submitBlockMsg struct { + blockHeader *types.BlockHeader + reply chan error +} // MiningPool is the support struct for p2p mine pool type MiningPool struct { - mutex sync.RWMutex - block *types.Block + mutex sync.RWMutex + block *types.Block + submitCh chan *submitBlockMsg chain *protocol.Chain accountManager *account.Manager @@ -30,6 +39,7 @@ type MiningPool struct { // NewMiningPool will create a new MiningPool func NewMiningPool(c *protocol.Chain, accountManager *account.Manager, txPool *protocol.TxPool, newBlockCh chan *bc.Hash) *MiningPool { m := &MiningPool{ + submitCh: make(chan *submitBlockMsg, maxSubmitChSize), chain: c, accountManager: accountManager, txPool: txPool, @@ -42,8 +52,18 @@ func NewMiningPool(c *protocol.Chain, accountManager *account.Manager, txPool *p // blockUpdater is the goroutine for keep update mining block func (m *MiningPool) blockUpdater() { ticker := time.NewTicker(time.Millisecond * blockUpdateMS) - for _ = range ticker.C { - m.generateBlock() + for { + select { + case <-ticker.C: + m.generateBlock() + + case submitMsg := <-m.submitCh: + err := m.submitWork(submitMsg.blockHeader) + if err != nil { + m.generateBlock() + } + submitMsg.reply <- err + } } } @@ -77,6 +97,12 @@ func (m *MiningPool) GetWork() (*types.BlockHeader, error) { // SubmitWork will try to submit the result to the blockchain func (m *MiningPool) SubmitWork(bh *types.BlockHeader) error { + reply := make(chan error, 1) + m.submitCh <- &submitBlockMsg{blockHeader: bh, reply: reply} + return <-reply +} + +func (m *MiningPool) submitWork(bh *types.BlockHeader) error { m.mutex.Lock() defer m.mutex.Unlock() -- 2.11.0