fix blockchain index builder data race
@@ -40,6 +40,7 @@ func init() {
type IndexBuilder struct {
store db.KVStore
pendingBlks chan *block.Block
+ cancelChan chan interface{}
timerFactory *prometheustimer.TimerFactory
}
@@ -61,6 +62,7 @@ func NewIndexBuilder(chain Blockchain) (*IndexBuilder, error) {
return &IndexBuilder{
store: bc.dao.kvstore,
pendingBlks: make(chan *block.Block, 64), // Actually 1 should be enough
+ cancelChan: make(chan interface{}),
timerFactory: timerFactory,
}, nil
}
@@ -68,7 +70,11 @@ func NewIndexBuilder(chain Blockchain) (*IndexBuilder, error) {
// Start starts the index builder
func (ib *IndexBuilder) Start(_ context.Context) error {
go func() {
- for blk := range ib.pendingBlks {
+ for {
+ select {
+ case <-ib.cancelChan:
+ return
+ case blk := <-ib.pendingBlks:
timer := ib.timerFactory.NewTimer("indexBlock")
batch := db.NewBatch()
if err := indexBlock(ib.store, blk, batch); err != nil {
@@ -96,13 +102,14 @@ func (ib *IndexBuilder) Start(_ context.Context) error {
}
timer.End()
}
+ }
}()
return nil
}
// Stop stops the index builder
func (ib *IndexBuilder) Stop(_ context.Context) error {
- close(ib.pendingBlks)
+ close(ib.cancelChan)
return nil
}
