github.com/bruceshao/lockfree@v1.1.3-0.20230816090528-e89824c0a6e9/sequencer.go (about)

     1  /*
     2   * Copyright (C) THL A29 Limited, a Tencent company. All rights reserved.
     3   *
     4   * SPDX-License-Identifier: Apache-2.0
     5   *
     6   */
     7  
     8  package lockfree
     9  
    10  import (
    11  	"sync/atomic"
    12  )
    13  
    14  // sequencer 序号产生器,维护读和写两个状态,写状态具体由内部游标(cursor)维护。
    15  // 读取状态由自身维护,变量read即可
    16  type sequencer struct {
    17  	rc       uint64 // 读取游标,因为该值仅会被一个g修改,所以不需要使用cursor
    18  	capacity uint64
    19  	wc       *cursor
    20  }
    21  
    22  func newSequencer(capacity int) *sequencer {
    23  	return &sequencer{
    24  		wc:       newCursor(),
    25  		rc:       1,
    26  		capacity: uint64(capacity),
    27  	}
    28  }
    29  
    30  // nextRead 获取下个要读取的位置
    31  // 使用原子操作解决data race问题
    32  func (s *sequencer) nextRead() uint64 {
    33  	return atomic.LoadUint64(&s.rc)
    34  }
    35  
    36  func (s *sequencer) readIncrement() uint64 {
    37  	return atomic.AddUint64(&s.rc, 1)
    38  }