xref: /aosp_15_r20/external/tensorflow/tensorflow/core/kernels/batching_util/fake_clock_env.h (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 #ifndef TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_FAKE_CLOCK_ENV_H_
17 #define TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_FAKE_CLOCK_ENV_H_
18 
19 #include <functional>
20 #include <string>
21 #include <vector>
22 
23 #include "tensorflow/core/lib/core/notification.h"
24 #include "tensorflow/core/lib/core/status.h"
25 #include "tensorflow/core/platform/env.h"
26 #include "tensorflow/core/platform/macros.h"
27 #include "tensorflow/core/platform/mutex.h"
28 #include "tensorflow/core/platform/thread_annotations.h"
29 #include "tensorflow/core/platform/types.h"
30 
31 namespace tensorflow {
32 namespace serving {
33 namespace test_util {
34 
35 // An Env implementation with a fake clock for NowMicros() and
36 // SleepForMicroseconds(). The clock doesn't advance on its own; it advances via
37 // an explicit Advance() method.
38 // All other Env virtual methods pass through to a wrapped Env.
39 class FakeClockEnv : public EnvWrapper {
40  public:
41   explicit FakeClockEnv(Env* wrapped);
42   ~FakeClockEnv() override = default;
43 
44   // Advance the clock by a certain number of microseconds.
45   void AdvanceByMicroseconds(int micros);
46 
47   // Blocks until there is a sleeping thread that is scheduled to wake up at
48   // the given (absolute) time.
49   void BlockUntilSleepingThread(uint64 wake_time);
50 
51   // Blocks until there are at least num_threads sleeping.
52   void BlockUntilThreadsAsleep(int num_threads);
53 
54   // Methods that this class implements.
55   uint64 NowMicros() const override;
56   void SleepForMicroseconds(int64_t micros) override;
57 
58  private:
59   mutable mutex mu_;
60 
61   uint64 current_time_ TF_GUARDED_BY(mu_) = 0;
62 
63   struct SleepingThread {
64     uint64 wake_time;
65     Notification* wake_notification;
66   };
67   std::vector<SleepingThread> sleeping_threads_ TF_GUARDED_BY(mu_);
68 
69   TF_DISALLOW_COPY_AND_ASSIGN(FakeClockEnv);
70 };
71 
72 }  // namespace test_util
73 }  // namespace serving
74 }  // namespace tensorflow
75 
76 #endif  // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_FAKE_CLOCK_ENV_H_
77