go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/sync/parallel/semaphore.go (about)

     1  // Copyright 2015 The LUCI Authors.
     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 parallel
    16  
    17  // SemaphoreToken is a semaphore token.
    18  type SemaphoreToken struct{}
    19  
    20  // Semaphore is a sync.Locker that implements a n-semaphore.
    21  //
    22  // Lock the semaphore acquires a semaphore token, possibly blocking until one
    23  // is available.
    24  //
    25  // Unlock releases an owned token, returning it to the semaphore.
    26  //
    27  // For semaphore s, len(s) is the current number of acquired resources, and
    28  // cap(s) is the total resource size of the semaphore.
    29  type Semaphore chan SemaphoreToken
    30  
    31  // Lock acquires a semaphore resource, blocking until one is available.
    32  func (s Semaphore) Lock() {
    33  	if cap(s) > 0 {
    34  		s <- SemaphoreToken{}
    35  	}
    36  }
    37  
    38  // Unlock releases a single semaphore resource.
    39  func (s Semaphore) Unlock() {
    40  	if cap(s) > 0 {
    41  		<-s
    42  	}
    43  }
    44  
    45  // TakeAll blocks until it holds all available semaphore resources. When it
    46  // returns, the caller owns all of the resources in the semaphore.
    47  func (s Semaphore) TakeAll() {
    48  	for i := 0; i < cap(s); i++ {
    49  		s.Lock()
    50  	}
    51  }