1 /* Copyright 2020 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_THREADSAFE_STATUS_H_ 17 #define TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_THREADSAFE_STATUS_H_ 18 19 #include "tensorflow/core/platform/mutex.h" 20 #include "tensorflow/core/platform/status.h" 21 #include "tensorflow/core/platform/thread_annotations.h" 22 23 namespace tensorflow { 24 // Wrapper class to allow both lock-free construction and concurrent updates on 25 // a 'status'. 26 // 27 // Example Usage: 28 // std::thread threads[2]; 29 // ThreadSafeStatus thread_safe_status; 30 // threads[0] = std::thread([&]() { 31 // status.Update(errors::Internal("internal error")); 32 // }); 33 // threads[1] = std::thread([&]() { 34 // status.Update(errors::InvalidArgument("invalid argument")); 35 // }); 36 // threads[0].Join(); 37 // threads[1].Join(); 38 // 39 // NOTE: 40 // When updated in a multi-threading setup, only the first error is retained. 41 class ThreadSafeStatus { 42 public: 43 const Status& status() const& TF_LOCKS_EXCLUDED(mutex_); 44 Status status() && TF_LOCKS_EXCLUDED(mutex_); 45 46 // Retains the first error status: replaces the current status with 47 // `new_status` if `new_status` is not OK and the previous status is OK. 48 void Update(const Status& new_status) TF_LOCKS_EXCLUDED(mutex_); 49 void Update(Status&& new_status) TF_LOCKS_EXCLUDED(mutex_); 50 51 private: 52 mutable mutex mutex_; 53 Status status_ TF_GUARDED_BY(mutex_); 54 }; 55 } // namespace tensorflow 56 57 #endif // TENSORFLOW_CORE_KERNELS_BATCHING_UTIL_THREADSAFE_STATUS_H_ 58