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 #ifndef TENSORFLOW_COMPILER_XLA_PJRT_SEMAPHORE_H_ 17 #define TENSORFLOW_COMPILER_XLA_PJRT_SEMAPHORE_H_ 18 19 #include "absl/synchronization/mutex.h" 20 #include "tensorflow/compiler/xla/types.h" 21 22 namespace xla { 23 24 class Semaphore { 25 public: 26 explicit Semaphore(int64_t capacity); 27 28 // Acquires `amount` units. Blocks until `amount` units are available. 29 void Acquire(int64_t amount); 30 31 // Returns `amount` units to the semaphore. 32 void Release(int64_t amount); 33 34 class ScopedReservation { 35 public: ScopedReservation(Semaphore * semaphore,int64_t amount)36 ScopedReservation(Semaphore* semaphore, int64_t amount) 37 : semaphore_(semaphore), amount_(amount) {} 38 ~ScopedReservation(); 39 40 ScopedReservation(const ScopedReservation&) = delete; 41 ScopedReservation(ScopedReservation&& other) noexcept; 42 ScopedReservation& operator=(const ScopedReservation&) = delete; 43 ScopedReservation& operator=(ScopedReservation&& other) noexcept; 44 45 private: 46 Semaphore* semaphore_; 47 int64_t amount_; 48 }; 49 // RAII version of Acquire. Releases the reservation when the 50 // ScopedReservation is destroyed. 51 ScopedReservation ScopedAcquire(int64_t amount); 52 53 private: 54 struct CanAcquireArgs { 55 Semaphore* semaphore; 56 int64_t amount; 57 }; 58 static bool CanAcquire(CanAcquireArgs* args) 59 ABSL_EXCLUSIVE_LOCKS_REQUIRED(args->semaphore->mu_); 60 61 absl::Mutex mu_; 62 int64_t value_ ABSL_GUARDED_BY(mu_); 63 }; 64 65 } // namespace xla 66 67 #endif // TENSORFLOW_COMPILER_XLA_PJRT_SEMAPHORE_H_ 68