github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/engine/pkg/quota/concurrency_quota.go (about)

     1  // Copyright 2022 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 quota
    15  
    16  import (
    17  	"context"
    18  
    19  	"github.com/pingcap/tiflow/pkg/errors"
    20  	"golang.org/x/sync/semaphore"
    21  )
    22  
    23  // ConcurrencyQuota abstracts an interface that supports acquire and release
    24  // quota concurrently
    25  type ConcurrencyQuota interface {
    26  	Consume(ctx context.Context) error
    27  	TryConsume() bool
    28  	Release()
    29  }
    30  
    31  // NewConcurrencyQuota creates a new concurrencyQuotaImpl instance that
    32  // implements ConcurrencyQuota interface
    33  func NewConcurrencyQuota(total int64) ConcurrencyQuota {
    34  	return &concurrencyQuotaImpl{sem: semaphore.NewWeighted(total)}
    35  }
    36  
    37  type concurrencyQuotaImpl struct {
    38  	sem *semaphore.Weighted
    39  }
    40  
    41  func (c *concurrencyQuotaImpl) Consume(ctx context.Context) error {
    42  	return errors.Trace(c.sem.Acquire(ctx, 1))
    43  }
    44  
    45  func (c *concurrencyQuotaImpl) TryConsume() bool {
    46  	return c.sem.TryAcquire(1)
    47  }
    48  
    49  func (c *concurrencyQuotaImpl) Release() {
    50  	c.sem.Release(1)
    51  }