github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/util/atomic.go (about)

     1  // Copyright 2024 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package util
    15  
    16  type numbers interface {
    17  	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | uintptr | float32 | float64
    18  }
    19  
    20  type genericAtomic[T numbers] interface {
    21  	Load() T
    22  	Store(T)
    23  	CompareAndSwap(old, new T) bool
    24  }
    25  
    26  // CompareAndIncrease updates the target if the new value is larger than or equal to the old value.
    27  // It returns false if the new value is smaller than the old value.
    28  func CompareAndIncrease[T numbers](target genericAtomic[T], new T) bool {
    29  	for {
    30  		old := target.Load()
    31  		if new < old {
    32  			return false
    33  		}
    34  		if new == old || target.CompareAndSwap(old, new) {
    35  			return true
    36  		}
    37  	}
    38  }
    39  
    40  // CompareAndMonotonicIncrease updates the target if the new value is larger than the old value.
    41  // It returns false if the new value is smaller than or equal to the old value.
    42  func CompareAndMonotonicIncrease[T numbers](target genericAtomic[T], new T) bool {
    43  	for {
    44  		old := target.Load()
    45  		if new <= old {
    46  			return false
    47  		}
    48  		if target.CompareAndSwap(old, new) {
    49  			return true
    50  		}
    51  	}
    52  }
    53  
    54  // MustCompareAndMonotonicIncrease updates the target if the new value is larger than the old value. It do nothing
    55  // if the new value is smaller than or equal to the old value.
    56  func MustCompareAndMonotonicIncrease[T numbers](target genericAtomic[T], new T) {
    57  	_ = CompareAndMonotonicIncrease(target, new)
    58  }