• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "tensorflow/compiler/xla/pjrt/event_pool.h"
17 
18 #include "absl/memory/memory.h"
19 #include "absl/synchronization/mutex.h"
20 #include "tensorflow/compiler/xla/status_macros.h"
21 
22 namespace xla {
23 
~Handle()24 EventPool::Handle::~Handle() {
25   if (pool_ && event_) {
26     absl::MutexLock lock(&pool_->mu_);
27     pool_->free_events_.push(std::move(event_));
28   }
29 }
30 
EventPool(bool allow_reuse)31 EventPool::EventPool(bool allow_reuse)
32     : allow_reuse_(allow_reuse), next_sequence_number_(0) {}
33 
AllocateEvent(se::StreamExecutor * executor)34 StatusOr<EventPool::Handle> EventPool::AllocateEvent(
35     se::StreamExecutor* executor) {
36   Handle event;
37 
38   if (allow_reuse_) {
39     event.pool_ = this;
40     absl::MutexLock lock(&mu_);
41     if (!free_events_.empty()) {
42       event.event_ = std::move(free_events_.top());
43       free_events_.pop();
44     }
45   }
46   if (!event.event_) {
47     event.event_ = absl::make_unique<se::Event>(executor);
48     TF_RET_CHECK(event.event_->Init()) << "Event initialization failed";
49   }
50   return event;
51 }
52 
ThenRecordEvent(se::Stream * stream,EventPool::Handle & handle)53 void EventPool::ThenRecordEvent(se::Stream* stream, EventPool::Handle& handle) {
54   absl::MutexLock lock(&mu_);
55   stream->ThenRecordEvent(handle.event_.get());
56   handle.sequence_number_ = next_sequence_number_++;
57 }
58 
ThenAllocateAndRecordEvent(se::Stream * stream)59 StatusOr<EventPool::Handle> EventPool::ThenAllocateAndRecordEvent(
60     se::Stream* stream) {
61   TF_ASSIGN_OR_RETURN(EventPool::Handle handle,
62                       AllocateEvent(stream->parent()));
63   ThenRecordEvent(stream, handle);
64   return handle;
65 }
66 
67 }  // namespace xla
68