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