1 /* Copyright 2019 The TensorFlow Authors. All Rights Reserved. 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 16 #include "tensorflow/compiler/xla/pjrt/semaphore.h" 17 18 #include "tensorflow/core/platform/logging.h" 19 20 namespace xla { 21 Semaphore(int64_t capacity)22Semaphore::Semaphore(int64_t capacity) : value_(capacity) { 23 CHECK_GE(capacity, 0); 24 } 25 CanAcquire(CanAcquireArgs * args)26bool Semaphore::CanAcquire(CanAcquireArgs* args) { 27 return args->semaphore->value_ >= args->amount; 28 } 29 Acquire(int64_t amount)30void Semaphore::Acquire(int64_t amount) { 31 CHECK_GE(amount, 0); 32 33 CanAcquireArgs args; 34 args.semaphore = this; 35 args.amount = amount; 36 37 mu_.LockWhen(absl::Condition(&CanAcquire, &args)); 38 value_ -= amount; 39 mu_.Unlock(); 40 } 41 Release(int64_t amount)42void Semaphore::Release(int64_t amount) { 43 CHECK_GE(amount, 0); 44 absl::MutexLock lock(&mu_); 45 value_ += amount; 46 } 47 ~ScopedReservation()48Semaphore::ScopedReservation::~ScopedReservation() { 49 if (semaphore_) { 50 semaphore_->Release(amount_); 51 } 52 } 53 ScopedReservation(ScopedReservation && other)54Semaphore::ScopedReservation::ScopedReservation( 55 ScopedReservation&& other) noexcept { 56 semaphore_ = other.semaphore_; 57 amount_ = other.amount_; 58 other.semaphore_ = nullptr; 59 } 60 operator =(ScopedReservation && other)61Semaphore::ScopedReservation& Semaphore::ScopedReservation::operator=( 62 ScopedReservation&& other) noexcept { 63 semaphore_ = other.semaphore_; 64 amount_ = other.amount_; 65 other.semaphore_ = nullptr; 66 return *this; 67 } 68 ScopedAcquire(int64_t amount)69Semaphore::ScopedReservation Semaphore::ScopedAcquire(int64_t amount) { 70 Acquire(amount); 71 return ScopedReservation(this, amount); 72 } 73 74 } // namespace xla 75