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)

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