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