Skip to content

Commit

Permalink
Resolve some comments
Browse files Browse the repository at this point in the history
Signed-off-by: caojiamingalan <[email protected]>
  • Loading branch information
CaojiamingAlan committed Jun 7, 2023
1 parent e5ac368 commit 72e5c3d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
7 changes: 4 additions & 3 deletions raft.go
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,9 @@ type raft struct {
// MsgPreVoteResp. See the comment in raft.send for details.
msgsAfterAppend []pb.Message
// msgsAfterAppendPool is a pool for msgsAfterAppend to avoid frequently
// reallocating the underlying array
// reallocating the underlying array. When assigning a new slice to msgsAfterAppend,
// we should try to get it from the pool first; before releasing the msgsAfterAppend
// slice, we should put the underlying array into the pool.
msgsAfterAppendPool *sync.Pool
// the leader id
lead uint64
Expand Down Expand Up @@ -428,8 +430,7 @@ func newRaft(c *Config) *raft {
disableProposalForwarding: c.DisableProposalForwarding,
msgsAfterAppendPool: &sync.Pool{
New: func() interface{} {
sl := make([]pb.Message, 0, 8)
return sl
return make([]pb.Message, 0, 8)
},
},
}
Expand Down
18 changes: 13 additions & 5 deletions rawnode.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,11 +253,18 @@ func newStorageAppendMsg(r *raft, rd Ready) pb.Message {
// handling to use a fast-path in r.raftLog.term() before the newly appended
// entries are removed from the unstable log.

//msgsAfterAppend is a pooled slice, so we need to make a deep copy
m.Responses = make([]pb.Message, len(r.msgsAfterAppend))
copy(m.Responses, r.msgsAfterAppend)
// msgsAfterAppend is a pooled slice, so we need to make a deep copy
msgsCount, needResp := len(r.msgsAfterAppend), false
if needStorageAppendRespMsg(r, rd) {
m.Responses = append(m.Responses, newStorageAppendRespMsg(r, rd))
msgsCount++
needResp = true
}
if msgsCount != 0 {
// NB: allocating precisely as much as needed.
m.Responses = append(make([]pb.Message, 0, msgsCount), r.msgsAfterAppend...)
if needResp {
m.Responses = append(m.Responses, newStorageAppendRespMsg(r, rd))
}
}
return m
}
Expand Down Expand Up @@ -431,7 +438,8 @@ func (rn *RawNode) acceptReady(rd Ready) {
}
}
rn.raft.msgs = nil
//release the msgsAfterAppend slice and put it into the msgsAfterAppendPool
// Release the msgsAfterAppend slice and put it back into the msgsAfterAppendPool.
// This clears the slice but reserves the underlying array, which we can pool and reuse.
if cap(rn.raft.msgsAfterAppend) > 0 {
rn.raft.msgsAfterAppendPool.Put(rn.raft.msgsAfterAppend[:0])
}
Expand Down

0 comments on commit 72e5c3d

Please sign in to comment.