github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/dm/master/scheduler/latch.go (about)

     1  // Copyright 2021 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 scheduler
    15  
    16  import (
    17  	"sync"
    18  
    19  	"github.com/pingcap/errors"
    20  )
    21  
    22  // latches provides a simple way to block concurrent accessing to one resource, if caller tries to acquire latch before
    23  // accessing resources.
    24  type latches struct {
    25  	mu    sync.Mutex
    26  	inUse map[string]struct{}
    27  	// TODO: use map[string]semaphore to implement a blocking acquire
    28  }
    29  
    30  // ReleaseFunc wraps on releasing a latch.
    31  // It is safe to call multiple times. Also compiler can warn you of not used ReleaseFunc variables.
    32  type ReleaseFunc func()
    33  
    34  func newLatches() *latches {
    35  	return &latches{
    36  		inUse: map[string]struct{}{},
    37  	}
    38  }
    39  
    40  func (l *latches) tryAcquire(name string) (ReleaseFunc, error) {
    41  	l.mu.Lock()
    42  	defer l.mu.Unlock()
    43  	if _, ok := l.inUse[name]; ok {
    44  		return nil, errors.Errorf("latch %s is in use by other client", name)
    45  	}
    46  
    47  	l.inUse[name] = struct{}{}
    48  	var once sync.Once
    49  	return func() {
    50  		once.Do(func() {
    51  			l.release(name)
    52  		})
    53  	}, nil
    54  }
    55  
    56  // release should not be called directly, it's recommended to wrap it with ReleaseFunc to avoid release a latch that not
    57  // belongs to caller.
    58  func (l *latches) release(name string) {
    59  	l.mu.Lock()
    60  	delete(l.inUse, name)
    61  	l.mu.Unlock()
    62  }