From 618065895b9ec3170eeb954bd12f8de58255e5c6 Mon Sep 17 00:00:00 2001 From: Bas van Kervel Date: Tue, 8 Sep 2015 11:27:55 +0200 Subject: [PATCH 1/2] agent/miner Prevent the CpuAgent to be started multiple times --- miner/agent.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/miner/agent.go b/miner/agent.go index 2f8d9fee4..c3ea91b50 100644 --- a/miner/agent.go +++ b/miner/agent.go @@ -23,6 +23,7 @@ import ( "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger/glog" "github.com/ethereum/go-ethereum/pow" + "sync/atomic" ) type CpuAgent struct { @@ -35,6 +36,8 @@ type CpuAgent struct { index int pow pow.PoW + + isMining int32 // isMining indicates whether the agent is currently mining } func NewCpuAgent(index int, pow pow.PoW) *CpuAgent { @@ -58,8 +61,12 @@ func (self *CpuAgent) Stop() { } func (self *CpuAgent) Start() { - self.mu.Lock() defer self.mu.Unlock() + self.mu.Lock() + + if atomic.LoadInt32(&self.isMining) == 1 { + return // agent already started + } self.quit = make(chan struct{}) // creating current op ch makes sure we're not closing a nil ch @@ -67,6 +74,8 @@ func (self *CpuAgent) Start() { self.workCh = make(chan *Work, 1) go self.update() + + atomic.StoreInt32(&self.isMining, 1) } func (self *CpuAgent) update() { @@ -99,10 +108,11 @@ done: case <-self.workCh: default: close(self.workCh) - break done } } + + atomic.StoreInt32(&self.isMining, 0) } func (self *CpuAgent) mine(work *Work, stop <-chan struct{}) { From 652eea71febb8ae39cde9d72c1d4a74e193ec55e Mon Sep 17 00:00:00 2001 From: Bas van Kervel Date: Tue, 8 Sep 2015 12:42:29 +0200 Subject: [PATCH 2/2] put unlock after lock --- miner/agent.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/miner/agent.go b/miner/agent.go index c3ea91b50..7ccf8d2e0 100644 --- a/miner/agent.go +++ b/miner/agent.go @@ -61,10 +61,10 @@ func (self *CpuAgent) Stop() { } func (self *CpuAgent) Start() { - defer self.mu.Unlock() self.mu.Lock() - - if atomic.LoadInt32(&self.isMining) == 1 { + defer self.mu.Unlock() + + if !atomic.CompareAndSwapInt32(&self.isMining, 0, 1) { return // agent already started } @@ -74,8 +74,6 @@ func (self *CpuAgent) Start() { self.workCh = make(chan *Work, 1) go self.update() - - atomic.StoreInt32(&self.isMining, 1) } func (self *CpuAgent) update() {