主頁 > 後端開發 > etcd/raft選舉原始碼解讀

etcd/raft選舉原始碼解讀

2023-04-09 07:50:48 後端開發

ETCD-raft筆記

0. 引言

該篇博客基于etcd v3.5.7版本,首先會簡單介紹etcd/raft對Raft選舉部分的演算法優化,然后通過原始碼分析etcd/raft的選舉實作,

1. etcd對于raft選舉演算法優化措施

該優化措施均在raft博士論文中有講解

etcd/raft實作的與選舉有關的優化有Pre-VoteCheck Quorum、和Leader Lease,在這三種優化中,只有Pre-VoteLeader Lease最初是對選舉程序的優化,Check Quorum是為了更高效地實作線性一致性讀(Linearizable Read)而做出的優化,但是由于Leader Lease需要依賴Check Quorum,因此也放在這講,

1.1 Pre-Vote

如下圖所示,當Raft集群的網路發生磁區時,會出現節點數達不到quorum(達成共識至少需要的節點數)的磁區,如圖中的Partition 1

網路磁區示意圖

在節點數能夠達到quorum的磁區中,選舉流程會正常進行,該磁區中的所有節點的term最侄訓穩定為新選舉出的leader節點的term,不幸的是,在節點數無法達到quorum的磁區中,如果該磁區中沒有leader節點,因為節點總是無法收到數量達到quorum的投票而不會選舉出新的leader,所以該磁區中的節點在election timeout超時后,會增大term并發起下一輪選舉,這導致該磁區中的節點的term會不斷增大,

如果網路一直沒有恢復,這是沒有問題的,但是,如果網路磁區恢復,此時,達不到quorum的磁區中的節點的term值會遠大于能夠達到quorum的磁區中的節點的term,這會導致能夠達到quorum的磁區的leader退位(step down)并增大自己的term到更大的term,使集群產生一輪不必要的選舉,

Pre-Vote機制就是為了解決這一問題而設計的,其解決的思路在于不允許達不到quorum的磁區正常進入投票流程,也就避免了其term號的增大,為此,Pre-Vote引入了“預投票”,也就是說,當節點election timeout超時時,它們不會立即增大自身的term并請求投票,而是先發起一輪預投票,收到預投票請求的節點不會退位,只有當節點收到了達到quorum的預投票回應時,節點才能增大自身term號并發起投票請求,這樣,達不到quorum的磁區中的節點永遠無法增大term,也就不會在磁區恢復后引起不必要的一輪投票,

1.2 Check Quorum

在Raft演算法中,保證線性一致性讀取的最簡單的方式,就是講讀請求同樣當做一條Raft提議,通過與其它日志相同的方式執行,因此這種方式也叫作Log Read,顯然,Log Read的性能很差,而在很多系統中,讀多寫少的負載是很常見的場景,因此,為了提高讀取的性能,就要試圖繞過日志機制,

但是,直接繞過日志機制從leader讀取,可能會讀到陳舊的資料,也就是說存在stale read的問題,在下圖的場景中,假設網路磁區前,Node 5是整個集群的leader,在網路發生磁區后,Partition 0磁區中選舉出了新leader,也就是圖中的Node 1

stale read示意圖

但是,由于網路磁區,Node 5無法收到Partition 0中節點的訊息,Node 5不會意識到集群中出現了新的leader,此時,雖然它不能成功地完成日志提交,但是如果讀取時繞過了日志,它還是能夠提供讀取服務的,這會導致連接到Node 5的client讀取到陳舊的資料,

Check Quorum可以減輕這一問題帶來的影響,其機制也非常簡單:讓leader每隔一段時間主動地檢查follower是否活躍,如果活躍的follower數量達不到quorum,那么說明該leader可能是磁區前的舊leader,所以此時該leader會主動退位轉為follower,

需要注意的是,Check Quorum并不能完全避免stale read的發生,只能減小其發生時間,降低影響,如果需要嚴格的線性一致性,需要通過其它機制實作,

1.3 Leader Lease

分布式系統中的網路環境十分復雜,有時可能出現網路不完全磁區的情況,即整個整個網路拓補圖是一個連通圖,但是可能并非任意的兩個節點都能互相訪問,

不完全磁區示意圖

這種現象不止會出現在網路故障中,還會出現在成員變更中,在通過ConfChange移除節點時,不同節點應用該ConfChange的時間可能不同,這也可能導致這一現象發生——TODO (舉個例子),

在上圖的場景下,Node 1Node 2之間無法通信,如果它們之間的通信中斷前,Node 1是集群的leader,在通信中斷后,Node 2無法再收到來自Node 1的心跳,因此,Node 2會開始選舉,如果在Node 2發起選舉前,Node 1Node 3中都沒有新的日志,那么Node 2仍可以收到能達到quorum的投票(來自Node 2本身的投票和來自Node 3的投票),并成為leader,

Leader Lease機制對投票引入了一條新的約束以解決這一問題:當節點在election timeout超時前,如果收到了leader的訊息,那么它不會為其它發起投票或預投票請求的節點投票,也就是說,Leader Lease機制會阻止了正常作業的集群中的節點給其它節點投票,

Leader Lease需要依賴Check Quorum機制才能正常作業,接下來筆者通過一個例子說明其原因,

假如在一個5個節點組成的Raft集群中,出現了下圖中的磁區情況:Node 1Node 2互通,Node 3Node 4Node 5之間兩兩互通、Node 5與任一節點不通,在網路磁區前,Node 1是集群的leader,

一種可能的網路磁區示意圖

在既沒有Leader Lease也沒有Check Quorum的情況下,Node 3Node 4會因收不到leader的心跳而發起投票,因為Node 2Node 3Node 4互通,該磁區節點數能達到quorum,因此它們可以選舉出新的leader,

而在使用了Leader Lease而不使用Check Quorum的情況下,由于Node 2仍能夠收到原leader Node 1的心跳,受Leader Lease機制的約束,它不會為其它節點投票,這會導致即使整個集群中存在可用節點數達到quorum的磁區,但是集群仍無法正常作業,

而如果同時使用了Leader LeaseCheck Quorum,那么在上圖的情況下,Node 1會在election timeout超時后因檢測不到數量達到quorum的活躍節點而退位為follower,這樣,Node 2Node 3Node 4之間的選舉可以正常進行,

1.4 引入的新問題與解決方案

引入Pre-VoteCheck Quorum(etcd/raft的實作中,開啟Check Quorum會自動開啟Leader Lease)會為Raft演算法引入一些新的問題,

當一個節點收到了term比自己低的訊息時,原本的邏輯是直接忽略該訊息,因為term比自己低的訊息僅可能是因網路延遲的遲到的舊訊息,然而,開啟了這些機制后,在如下的場景中會出現問題:

場景1示意圖

場景1: 如上圖所示,在開啟了Check Quorum / Leader Lease后(假設沒有開啟Pre-VotePre-Vote的問題在下一場景中討論),數量達不到quorum的磁區中的leader會退位,且該磁區中的節點永遠都無法選舉出leader,因此該磁區的節點的term會不斷增大,當該磁區與整個集群的網路恢復后,由于開啟了Check Quorum / Leader Lease,即使該磁區中的節點有更大的term,由于原磁區的節點作業正常,它們的選舉請求會被丟棄,同時,由于該節點的term比原磁區的leader節點的term大,因此它會丟棄原磁區的leader的請求,這樣,該節點永遠都無法重新加入集群,也無法當選新leader,(詳見issue #5451、issue #5468),

場景2示意圖

場景2: Pre-Vote機制也有類似的問題,如上圖所示,假如發起預投票的節點,在預投票通過后正要發起正式投票的請求時出現網路磁區,此時,該節點的term會高于原集群的term,而原集群因沒有收到真正的投票請求,不會更新term,繼續正常運行,在網路磁區恢復后,原集群的term低于磁區節點的term,但是日志比磁區節點更新,此時,該節點發起的預投票請求因沒有日志落后會被丟棄,而原集群leader發給該節點的請求會因term比該節點小而被丟棄,同樣,該節點永遠都無法重新加入集群,也無法當選新leader,(詳見issue #8501、issue #8525),

場景3: 在更復雜的情況中,比如,在變更配置時,開啟了原本沒有開啟的Pre-Vote機制,此時可能會出現與上一條類似的情況,即可能因term更高但是log更舊的節點的存在導致整個集群的死鎖,所有節點都無法預投票成功,這種情況比上一種情況更危險,上一種情況只有之前磁區的節點無法加入集群,在這種情況下,整個集群都會不可用,(詳見issue #8501、issue #8525),

為了解決以上問題,節點在收到term比自己低的請求時,需要做特殊的處理,處理邏輯也很簡單:

  1. 如果收到了term比當前節點term低的leader的訊息,且集群開啟了Check Quorum / Leader LeasePre-Vote,那么發送一條term為當前term的訊息,令term低的節點成為follower,(針對場景1場景2
  2. 對于term比當前節點term低的預投票請求,無論是否開啟了Check Quorum / Leader LeasePre-Vote,都要通過一條term為當前term的訊息,迫使其轉為follower并更新term,(針對場景3

2. etcd中Raft選舉的實作

2.1 發起vote或pre-vote流程

2.1.1 Election timeout

在集群剛啟動時,所有節點的狀態都為 follower,等待超時觸發 leader election,超時時間由 Config 設定,etcd/raft 沒有用真實時間而是使用邏輯時鐘,當呼叫 tick 的次數超過指定次數時觸發超時事件, 對于 followercandidate 而言,tick 中會判斷是否超時,若超時則會本地生成一個 MsgHup 型別的訊息觸發 leader election:

// tickElection is run by followers and candidates after r.electionTimeout.
func (r *raft) tickElection() {
	r.electionElapsed++

	if r.promotable() && r.pastElectionTimeout() {
		r.electionElapsed = 0
		r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
	}
}

2.1.2 MsgHup訊息處理與hup方法

etcd/raft通過raft結構體的Step方法實作Raft狀態機的狀態轉移,Step 方法是訊息處理的入口,不同 state 處理的訊息不同且處理方式不同,所以有多個 step 方法:

  • raft.Step(): 訊息處理的入口,做一些共性的檢查,如 term,或處理所有狀態都需要處理的訊息,若需要更進一步處理,會根據狀態 呼叫下面的方法:
    • raft.stepLeader(): leader 狀態的訊息處理方法;
    • raft.stepFollower(): follower 狀態的訊息處理方法;
    • raft.stepCandidate(): candidate 狀態的訊息處理方法,
func (r *raft) Step(m pb.Message) error {
	// ... ...
	switch m.Type {
	case pb.MsgHup:
		if r.preVote {
			r.hup(campaignPreElection)
		} else {
			r.hup(campaignElection)
		}
	// ... ...
	}
	// ... ...
}

Step方法在處理MsgHup訊息時,會根據當前配置中是否開啟了Pre-Vote機制,以不同的CampaignType呼叫hup方法,CampaignType是一種列舉型別(go語言的列舉實作方式),其可能值如下表所示,

描述
campaignPreElection 表示Pre-Vote的預選舉階段,
campaignElection 表示正常的選舉階段(僅超時選舉,不包括Leader Transfer),
campaignTransfer 表示Leader Transfer階段,

接下來對hup的實作進行分析,

func (r *raft) hup(t CampaignType) {
	if r.state == StateLeader {
		r.logger.Debugf("%x ignoring MsgHup because already leader", r.id)
		return
	}

	if !r.promotable() {
		r.logger.Warningf("%x is unpromotable and can not campaign", r.id)
		return
	}
	ents, err := r.raftLog.slice(r.raftLog.applied+1, r.raftLog.committed+1, noLimit)
	if err != nil {
		r.logger.Panicf("unexpected error getting unapplied entries (%v)", err)
	}
	if n := numOfPendingConf(ents); n != 0 && r.raftLog.committed > r.raftLog.applied {
		r.logger.Warningf("%x cannot campaign at term %d since there are still %d pending configuration changes to apply", r.id, r.Term, n)
		return
	}

	r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term)
	r.campaign(t)
}
// promotable indicates whether state machine can be promoted to leader,
// which is true when its own id is in progress list.
func (r *raft) promotable() bool {
	pr := r.prs.Progress[r.id]
	return pr != nil && !pr.IsLearner && !r.raftLog.hasPendingSnapshot()
}

總結當節點出現以下情況時不能發起選舉:

  1. 節點被移出集群
  2. 節點是learner
  3. 節點還有未保存到穩定存盤的snapshot
  4. 節點有還未被應用的集群配置變更ConfChange訊息

2.1.3 campaign

官方注釋很詳細了,因此不多廢筆墨解釋

// campaign transitions the raft instance to candidate state. This must only be
// called after verifying that this is a legitimate transition.
func (r *raft) campaign(t CampaignType) {
    // 因為呼叫campaign的方法不止有hup,campaign方法首先還是會檢查promotable()是否為真,
	if !r.promotable() {
		// This path should not be hit (callers are supposed to check), but
		// better safe than sorry.
		r.logger.Warningf("%x is unpromotable; campaign() should have been called", r.id)
	}
	var term uint64
	var voteMsg pb.MessageType
	if t == campaignPreElection {
		r.becomePreCandidate()
		voteMsg = pb.MsgPreVote
		// PreVote RPCs are sent for the next term before we've incremented r.Term.
		term = r.Term + 1
	} else {
		r.becomeCandidate()
		voteMsg = pb.MsgVote
		term = r.Term
	}
	if _, _, res := r.poll(r.id, voteRespMsgType(voteMsg), true); res == quorum.VoteWon {
		// We won the election after voting for ourselves (which must mean that
		// this is a single-node cluster). Advance to the next state.
		if t == campaignPreElection {
			r.campaign(campaignElection)
		} else {
			r.becomeLeader()
		}
		return
	}
	var ids []uint64
	{
		//won't send requestVote to learners, beacause learners[] are not in incoming[] and outgoing[]
		idMap := r.prs.Voters.IDs()
		ids = make([]uint64, 0, len(idMap))
		for id := range idMap {
			ids = append(ids, id)
		}
		sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
	}
	for _, id := range ids {
		if id == r.id {
			continue
		}
		r.logger.Infof("%x [logterm: %d, index: %d] sent %s request to %x at term %d",
			r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), voteMsg, id, r.Term)

		var ctx []byte
		if t == campaignTransfer {
			ctx = []byte(t)
		}
		r.send(pb.Message{Term: term, To: id, Type: voteMsg, Index: r.raftLog.lastIndex(), LogTerm: r.raftLog.lastTerm(), Context: ctx})
	}
}

至此,該節點已向其他節點發送MsgVote或MsgPreVote訊息

2.2 節點收到vote或pre-vote訊息處理流程

處理vote或pre-vote訊息都在Step方法內,不會進入各自的step方法,有效的MsgPreVote必須滿足其中一個條件(m.Term > r.Term)

官方注釋很詳細,簡單易理解,因此不多廢筆墨解釋

func (r *raft) Step(m pb.Message) error {
	// Handle the message term, which may result in our stepping down to a follower.
	switch {
	case m.Term == 0:
		// local message
	case m.Term > r.Term:
		if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote {
			force := bytes.Equal(m.Context, []byte(campaignTransfer))
			inLease := r.checkQuorum && r.lead != None && r.electionElapsed < r.electionTimeout
			if !force && inLease {
				// If a server receives a RequestVote request within the minimum election timeout
				// of hearing from a current leader, it does not update its term or grant its vote
				return nil
			}
		}
		switch {
		case m.Type == pb.MsgPreVote:
			// Never change our term in response to a PreVote
		case m.Type == pb.MsgPreVoteResp && !m.Reject:
			// We send pre-vote requests with a term in our future. If the
			// pre-vote is granted, we will increment our term when we get a
			// quorum. If it is not, the term comes from the node that
			// rejected our vote so we should become a follower at the new
			// term.
		default:
			if m.Type == pb.MsgApp || m.Type == pb.MsgHeartbeat || m.Type == pb.MsgSnap {
				r.becomeFollower(m.Term, m.From)
			} else {
				r.becomeFollower(m.Term, None)
			}
		}

	case m.Term < r.Term:
        // ........
	}

	switch m.Type {
	case pb.MsgHup:
        // ........
	case pb.MsgVote, pb.MsgPreVote:
		// We can vote if this is a repeat of a vote we've already cast...
		canVote := r.Vote == m.From ||
			// ...we haven't voted and we don't think there's a leader yet in this term...
			(r.Vote == None && r.lead == None) ||
			// ...or this is a PreVote for a future term...
			(m.Type == pb.MsgPreVote && m.Term > r.Term)
		// ...and we believe the candidate is up to date.
		if canVote && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
			// Note: it turns out that that learners must be allowed to cast votes.
			// This seems counter- intuitive but is necessary in the situation in which
			// a learner has been promoted (i.e. is now a voter) but has not learned
			// about this yet.
			// For example, consider a group in which id=1 is a learner and id=2 and
			// id=3 are voters. A configuration change promoting 1 can be committed on
			// the quorum `{2,3}` without the config change being appended to the
			// learner's log. If the leader (say 2) fails, there are de facto two
			// voters remaining. Only 3 can win an election (due to its log containing
			// all committed entries), but to do so it will need 1 to vote. But 1
			// considers itself a learner and will continue to do so until 3 has
			// stepped up as leader, replicates the conf change to 1, and 1 applies it.
			// Ultimately, by receiving a request to vote, the learner realizes that
			// the candidate believes it to be a voter, and that it should act
			// accordingly. The candidate's config may be stale, too; but in that case
			// it won't win the election, at least in the absence of the bug discussed
			// in:
			// https://github.com/etcd-io/etcd/issues/7625#issuecomment-488798263.

			// When responding to Msg{Pre,}Vote messages we include the term
			// from the message, not the local term. To see why, consider the
			// case where a single node was previously partitioned away and
			// it's local term is now out of date. If we include the local term
			// (recall that for pre-votes we don't update the local term), the
			// (pre-)campaigning node on the other end will proceed to ignore
			// the message (it ignores all out of date messages).
			// The term in the original message and current local term are the
			// same in the case of regular votes, but different for pre-votes.
			r.send(pb.Message{To: m.From, Term: m.Term, Type: voteRespMsgType(m.Type)})
			if m.Type == pb.MsgVote {
				// Only record real votes.
				r.electionElapsed = 0
				r.Vote = m.From
			}
		} else {
			r.send(pb.Message{To: m.From, Term: r.Term, Type: voteRespMsgType(m.Type), Reject: true})
		}

	default:
        // ...........
	}
	return nil
}

注意:節點同意投票訊息帶的是m.Term,拒絕投票訊息是r.Term,如果拒接MsgPreVote訊息,那么發送pre-vote訊息的節點就變為

r.Termfollower,在2.3.1節內體現

2.3 節點收到處理MsgPreVoteResp或MsgVoteResp訊息流程

2.3.1 Step內處理

根據2.2節可以看到Step內有這樣一段代碼:在2.2節最后有解釋,官方也給了詳細注釋

		switch {
		case m.Type == pb.MsgPreVote:
			// Never change our term in response to a PreVote
		case m.Type == pb.MsgPreVoteResp && !m.Reject:
			// We send pre-vote requests with a term in our future. If the
			// pre-vote is granted, we will increment our term when we get a
			// quorum. If it is not, the term comes from the node that
			// rejected our vote so we should become a follower at the new
			// term.
		default:
			if m.Type == pb.MsgApp || m.Type == pb.MsgHeartbeat || m.Type == pb.MsgSnap {
				r.becomeFollower(m.Term, m.From)
			} else {
				r.becomeFollower(m.Term, None)
			}
		}

2.3.2 stepCandidate內處理

	case myVoteRespType:
		gr, rj, res := r.poll(m.From, m.Type, !m.Reject)
		r.logger.Infof("%x has received %d %s votes and %d vote rejections", r.id, gr, m.Type, rj)
		switch res {
		case quorum.VoteWon:
			if r.state == StatePreCandidate {
				r.campaign(campaignElection)
			} else {
				r.becomeLeader()
				r.bcastAppend()
			}
		case quorum.VoteLost:
			// pb.MsgPreVoteResp contains future term of pre-candidate
			// m.Term > r.Term; reuse r.Term
			r.becomeFollower(r.Term, None)
		}

如果預投票成功,則發起新一輪正式投票,如果正式投票成功,則轉為leader,接著后續操作

2.4 轉變領導者身份

2.4.1 becomeLeader()

func (r *raft) becomeLeader() {
	// TODO(xiangli) remove the panic when the raft implementation is stable
	if r.state == StateFollower {
		panic("invalid transition [follower -> leader]")
	}
	r.step = stepLeader
	r.reset(r.Term)
	r.tick = r.tickHeartbeat
	r.lead = r.id
	r.state = StateLeader
	// Followers enter replicate mode when they've been successfully probed
	// (perhaps after having received a snapshot as a result). The leader is
	// trivially in this state. Note that r.reset() has initialized this
	// progress with the last index already.
	r.prs.Progress[r.id].BecomeReplicate()

	// Conservatively set the pendingConfIndex to the last index in the
	// log. There may or may not be a pending config change, but it's
	// safe to delay any future proposals until we commit all our
	// pending log entries, and scanning the entire tail of the log
	// could be expensive.
	r.pendingConfIndex = r.raftLog.lastIndex()

	emptyEnt := pb.Entry{Data: nil}
	if !r.appendEntry(emptyEnt) {
		// This won't happen because we just called reset() above.
		r.logger.Panic("empty entry was dropped")
	}
	// As a special case, don't count the initial empty entry towards the
	// uncommitted log quota. This is because we want to preserve the
	// behavior of allowing one entry larger than quota if the current
	// usage is zero.
	r.reduceUncommittedSize([]pb.Entry{emptyEnt})
	r.logger.Infof("%x became leader at term %d", r.id, r.Term)
}

candidate轉變為leader,需要在自己的log中append一條當前term的日志,并廣播給其他節點

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/549492.html

標籤:其他

上一篇:數字營銷(二)如何確定付費客戶特征?

下一篇:Java-SPI機制詳解

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more