xref: /aosp_15_r20/external/tensorflow/tensorflow/compiler/xla/pjrt/worker_thread.h (revision b6fb3261f9314811a0f4371741dbb8839866f948)
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 #ifndef TENSORFLOW_COMPILER_XLA_PJRT_WORKER_THREAD_H_
17 #define TENSORFLOW_COMPILER_XLA_PJRT_WORKER_THREAD_H_
18 
19 #include <functional>
20 #include <memory>
21 #include <queue>
22 #include <string>
23 
24 #include "absl/synchronization/mutex.h"
25 #include "tensorflow/core/platform/env.h"
26 
27 namespace xla {
28 
29 // A worker thread that runs a sequence of closures. Equivalent to a thread
30 // pool of size 1.
31 class WorkerThread {
32  public:
33   // 'name' is a name for the thread for debugging purposes.
34   WorkerThread(tensorflow::Env* env, const std::string& name);
35 
36   // Blocks until all enqueued closures have completed.
37   ~WorkerThread();
38 
39   // Adds 'fn' to the queue of closures to be executed by the worker thread.
40   void Schedule(std::function<void()> fn);
41 
42  private:
43   bool WorkAvailable() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
44   void WorkLoop();
45 
46   absl::Mutex mu_;
47   std::queue<std::function<void()>> work_queue_ ABSL_GUARDED_BY(mu_);
48 
49   std::unique_ptr<tensorflow::Thread> thread_;
50 };
51 
52 }  // namespace xla
53 
54 #endif  // TENSORFLOW_COMPILER_XLA_PJRT_WORKER_THREAD_H_
55