fabric peer節點賬本驗證器相關代碼解讀

賬本驗證器相關代碼

fabric/core/commiter/txvalidator/v20/validator.go

// Semaphore provides to the validator means for synchronisation 信號量向驗證器提供同步方式
type Semaphore interface {
	// Acquire implements semaphore-like acquire semantics Acquire() 實現類似信號量的獲取語義
	Acquire(ctx context.Context) error

	// Release implements semaphore-like release semantics Release() 實現了類似信號量的釋放語義
	Release()
}

fabric/common/semaphore/semaphore.go

// Acquire acquires a permit. This call will block until a permit is available
// or the provided context is completed.
// Acquire 獲得許可。 在許可可用或提供的上下文完成之前,此調用將阻塞。
//
// If the provided context is completed, the method will return the
// cancellation error.
// 如果提供的上下文完成,該方法將返回取消錯誤。
func (s Semaphore) Acquire(ctx context.Context) error {
	select {
        //在goroutine中,使用select調用<-ctx.Done()判斷是否要結束,如果接受到值的話,就可以返回結束goroutine了;如果接收不到,就會繼續進行監控。
	case <-ctx.Done():
		return ctx.Err()
        // 有時候使用 channel 不需要發送任何的數據,只用來通知子協程(goroutine)執行任務,或只用來控制協程併發度。這種情況下,使用空結構體作爲佔位符就非常合適了。
	case s <- struct{}{}:
		return nil
	}
}

fabric/core/commiter/txvalidator/v20/validator.go

func (v *TxValidator) Validate(block *common.Block) error {
...
  // ensure that we don't have too many concurrent validation workers
  // 設置併發數量,以保證驗證過程的安全性
  v.Semaphore.Acquire(context.Background())
...
}

參考

[1] 理解 golang 中的 context(上下文)包(https://zhuanlan.zhihu.com/p/163529509)
[2] Go語言實戰筆記(二十)| Go Context(https://www.flysnow.org/2017/05/12/go-in-action-go-context.html)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章