github.com/bruceshao/lockfree@v1.1.3-0.20230816090528-e89824c0a6e9/util.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  	"errors"
    12  	"reflect"
    13  	"runtime"
    14  	"unsafe"
    15  )
    16  
    17  const (
    18  	activeSpin       = 4
    19  	passiveSpin      = 2
    20  	READY            = 0 // 模块的状态之就绪态
    21  	RUNNING          = 1 // 模块的状态之运行态
    22  	StartErrorFormat = "start model [%s] error"
    23  	CloseErrorFormat = "close model [%s] error"
    24  )
    25  
    26  var (
    27  	ncpu        = runtime.NumCPU()
    28  	spin        = 0
    29  	ClosedError = errors.New("the queue has been closed")
    30  )
    31  
    32  func init() {
    33  	if ncpu > 1 {
    34  		spin = activeSpin
    35  	}
    36  }
    37  
    38  //go:linkname procyield runtime.procyield
    39  func procyield(cycles uint32)
    40  
    41  //go:linkname osyield runtime.osyield
    42  func osyield()
    43  
    44  // byteArrayPointerWithUint8 创建uint8切片,返回其对应实际内容(Data)的指针
    45  func byteArrayPointerWithUint8(capacity int) unsafe.Pointer {
    46  	bytes := make([]uint8, capacity)
    47  	rs := (*reflect.SliceHeader)(unsafe.Pointer(&bytes))
    48  	return unsafe.Pointer(rs.Data)
    49  }
    50  
    51  // byteArrayPointer 创建uint32切片,返回其对应实际内容(Data)的指针
    52  func byteArrayPointerWithUint32(capacity int) unsafe.Pointer {
    53  	bytes := make([]uint32, capacity)
    54  	rs := (*reflect.SliceHeader)(unsafe.Pointer(&bytes))
    55  	return unsafe.Pointer(rs.Data)
    56  }
    57  
    58  // byteArrayPointer 创建int64切片,返回其对应实际内容(Data)的指针
    59  func byteArrayPointerWithInt64(capacity int) unsafe.Pointer {
    60  	bytes := make([]int64, capacity)
    61  	rs := (*reflect.SliceHeader)(unsafe.Pointer(&bytes))
    62  	return unsafe.Pointer(rs.Data)
    63  }
    64  
    65  // minSuitableCap 最小的合适的数量
    66  func minSuitableCap(v int) int {
    67  	if v <= 0 {
    68  		return 2
    69  	}
    70  	v--
    71  	v |= v >> 1
    72  	v |= v >> 2
    73  	v |= v >> 4
    74  	v |= v >> 8
    75  	v |= v >> 16
    76  	v++
    77  	return v
    78  }