-
Notifications
You must be signed in to change notification settings - Fork 9
/
tx_batch.go
65 lines (57 loc) · 1.16 KB
/
tx_batch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package core
import (
"math"
"runtime"
"sync"
"sync/atomic"
"github.com/zvchain/zvchain/middleware/types"
)
type txBatchAdder struct {
pool types.TransactionPool
routineNum int
mu sync.Mutex
}
func newTxBatchAdder(pool types.TransactionPool) *txBatchAdder {
return &txBatchAdder{
pool: pool,
routineNum: runtime.NumCPU(),
}
}
func (tv *txBatchAdder) batchAdd(txs txSlice) error {
if len(txs) == 0 {
return nil
}
tv.mu.Lock()
defer tv.mu.Unlock()
wg := sync.WaitGroup{}
step := int(math.Ceil(float64(len(txs)) / float64(tv.routineNum)))
atomicErr := atomic.Value{}
for begin := 0; begin < len(txs); {
end := begin + step
if end > len(txs) {
end = len(txs)
}
copySlice := txs[begin:end]
wg.Add(1)
go func() {
defer wg.Done()
for _, tx := range copySlice {
if atomicErr.Load() != nil {
return
}
if err := tv.pool.AsyncAddTransaction(tx); err != nil {
atomicErr.Store(err)
Logger.Warnf("batch add tx error:%v, tx hash %v, source %v", err, tx.Hash, tx.Source)
return
}
}
}()
begin = end
}
wg.Wait()
e := atomicErr.Load()
if e != nil {
return e.(error)
}
return nil
}