github.com/matrixorigin/matrixone@v0.7.0/pkg/vm/engine/tae/buffer/limiter.go (about)

     1  // Copyright 2022 Matrix Origin
     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  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package buffer
    16  
    17  import (
    18  	"fmt"
    19  	"sync/atomic"
    20  )
    21  
    22  type sizeLimiter struct {
    23  	maxactivesize uint64
    24  	activesize    atomic.Uint64
    25  }
    26  
    27  func newSizeLimiter(maxactivesize uint64) *sizeLimiter {
    28  	return &sizeLimiter{
    29  		maxactivesize: maxactivesize,
    30  	}
    31  }
    32  
    33  func (l *sizeLimiter) RetuernQuota(size uint64) uint64 {
    34  	return l.activesize.Add(^uint64(size - 1))
    35  }
    36  
    37  func (l *sizeLimiter) ApplyQuota(size uint64) bool {
    38  	pre := l.activesize.Load()
    39  	post := pre + size
    40  	if post > l.maxactivesize {
    41  		return false
    42  	}
    43  	for !l.activesize.CompareAndSwap(pre, post) {
    44  		pre = l.activesize.Load()
    45  		post = pre + size
    46  		if post > l.maxactivesize {
    47  			return false
    48  		}
    49  	}
    50  	return true
    51  }
    52  
    53  func (l *sizeLimiter) Total() uint64 {
    54  	return l.activesize.Load()
    55  }
    56  
    57  func (l *sizeLimiter) String() string {
    58  	s := fmt.Sprintf("<sizeLimiter>[Size=(%d/%d)]",
    59  		l.Total(), l.maxactivesize)
    60  	return s
    61  }