• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "tensorflow/compiler/xla/service/stream_pool.h"
17 
18 #include "absl/memory/memory.h"
19 #include "tensorflow/core/platform/logging.h"
20 
21 namespace xla {
22 
BorrowStream(se::StreamExecutor * executor)23 StreamPool::Ptr StreamPool::BorrowStream(se::StreamExecutor* executor) {
24   std::unique_ptr<se::Stream> stream;
25   {
26     tensorflow::mutex_lock lock(mu_);
27     if (!streams_.empty()) {
28       // Re-use an existing stream from the pool.
29       stream = std::move(streams_.back());
30       streams_.pop_back();
31       if (stream->ok()) {
32         VLOG(1) << stream->DebugStreamPointers()
33                 << " StreamPool reusing existing stream";
34       } else {
35         VLOG(1) << stream->DebugStreamPointers()
36                 << " stream was not ok, StreamPool deleting";
37         stream = nullptr;
38       }
39     }
40   }
41 
42   if (!stream) {
43     // Create a new stream.
44     stream = absl::make_unique<se::Stream>(executor);
45     stream->Init();
46     VLOG(1) << stream->DebugStreamPointers()
47             << " StreamPool created new stream";
48   }
49 
50   // Return the stream wrapped in Ptr, which has our special deleter semantics.
51   PtrDeleter deleter = {this};
52   return Ptr(stream.release(), deleter);
53 }
54 
ReturnStream(se::Stream * stream)55 void StreamPool::ReturnStream(se::Stream* stream) {
56   if (stream->ok()) {
57     VLOG(1) << stream->DebugStreamPointers()
58             << " StreamPool returning ok stream";
59     tensorflow::mutex_lock lock(mu_);
60     streams_.emplace_back(stream);
61   } else {
62     // If the stream has encountered any errors, all subsequent operations on it
63     // will fail. So just delete the stream, and rely on new streams to be
64     // created in the future.
65     VLOG(1) << stream->DebugStreamPointers()
66             << " StreamPool deleting !ok stream";
67     delete stream;
68   }
69 }
70 
71 }  // namespace xla
72