xref: /aosp_15_r20/external/tensorflow/tensorflow/core/kernels/batching_util/fake_clock_env.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2016 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/core/kernels/batching_util/fake_clock_env.h"
17 
18 #include <string>
19 
20 namespace tensorflow {
21 namespace serving {
22 namespace test_util {
23 
FakeClockEnv(Env * wrapped)24 FakeClockEnv::FakeClockEnv(Env* wrapped) : EnvWrapper(wrapped) {}
25 
AdvanceByMicroseconds(int micros)26 void FakeClockEnv::AdvanceByMicroseconds(int micros) {
27   {
28     mutex_lock l(mu_);
29     current_time_ += micros;
30     for (auto it = sleeping_threads_.begin(); it != sleeping_threads_.end();) {
31       if (current_time_ >= it->wake_time) {
32         it->wake_notification->Notify();
33         it = sleeping_threads_.erase(it);
34       } else {
35         ++it;
36       }
37     }
38   }
39 }
40 
BlockUntilSleepingThread(uint64 wake_time)41 void FakeClockEnv::BlockUntilSleepingThread(uint64 wake_time) {
42   for (;;) {
43     {
44       mutex_lock l(mu_);
45       for (auto it = sleeping_threads_.begin(); it != sleeping_threads_.end();
46            ++it) {
47         if (it->wake_time == wake_time) {
48           return;
49         }
50       }
51     }
52     EnvWrapper::SleepForMicroseconds(100);
53   }
54 }
55 
BlockUntilThreadsAsleep(int num_threads)56 void FakeClockEnv::BlockUntilThreadsAsleep(int num_threads) {
57   for (;;) {
58     {
59       mutex_lock l(mu_);
60       if (num_threads <= sleeping_threads_.size()) {
61         return;
62       }
63     }
64     EnvWrapper::SleepForMicroseconds(100);
65   }
66 }
67 
NowMicros() const68 uint64 FakeClockEnv::NowMicros() const {
69   {
70     mutex_lock l(mu_);
71     return current_time_;
72   }
73 }
74 
SleepForMicroseconds(int64_t micros)75 void FakeClockEnv::SleepForMicroseconds(int64_t micros) {
76   if (micros == 0) {
77     return;
78   }
79 
80   Notification wake_notification;
81   {
82     mutex_lock l(mu_);
83     sleeping_threads_.push_back({current_time_ + micros, &wake_notification});
84   }
85   wake_notification.WaitForNotification();
86 }
87 
88 }  // namespace test_util
89 }  // namespace serving
90 }  // namespace tensorflow
91