1 /* Copyright 2018 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_SERVICE_STREAM_POOL_H_ 17 #define TENSORFLOW_COMPILER_XLA_SERVICE_STREAM_POOL_H_ 18 19 #include <memory> 20 #include <vector> 21 22 #include "tensorflow/compiler/xla/types.h" 23 #include "tensorflow/core/platform/stream_executor_no_cuda.h" 24 25 namespace xla { 26 27 // Pool of stream_executor::Streams, which are created as needed and 28 // destroyed when the pool is destroyed. 29 class StreamPool { 30 public: 31 struct PtrDeleter { operatorPtrDeleter32 void operator()(se::Stream* stream) { pool->ReturnStream(stream); } 33 StreamPool* pool; 34 }; 35 36 // Stream pointer type returned by BorrowStream, which returns the 37 // stream to the pool on destruction. 38 using Ptr = std::unique_ptr<se::Stream, PtrDeleter>; 39 StreamPool()40 StreamPool() {} 41 42 // Returns a pointer to a stream in the pool, creating a new stream 43 // if none are available in the pool. The returned smart pointer 44 // returns the stream to the pool on destruction. 45 // 46 // This method is thread-safe. 47 Ptr BorrowStream(se::StreamExecutor* executor); 48 49 private: 50 // Puts a pointer to a stream back into the pool, leaving it free 51 // for future use. Streams that have previously encountered errors 52 // are deleted, and not returned to the pool. 53 // 54 // This method is thread-safe. 55 void ReturnStream(se::Stream* stream); 56 57 absl::Mutex mu_; 58 std::vector<std::unique_ptr<se::Stream>> streams_ ABSL_GUARDED_BY(mu_); 59 }; 60 61 } // namespace xla 62 63 #endif // TENSORFLOW_COMPILER_XLA_SERVICE_STREAM_POOL_H_ 64