1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 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 UTILS_INCLUDE_PROMISE_H 17 #define UTILS_INCLUDE_PROMISE_H 18 19 #include <condition_variable> 20 #include <thread> 21 22 #include <refbase.h> 23 24 namespace OHOS { 25 template<class T> 26 class Promise : public RefBase { 27 public: 28 Promise() = default; 29 Promise(const T& t); 30 virtual ~Promise() = default; 31 32 virtual bool IsResolved() const; 33 virtual const T &Await(); 34 virtual void Then(std::function<void(const T &t)> func); 35 virtual bool Resolve(const T &t); 36 37 private: 38 bool resolved = false; 39 std::mutex mutex; 40 std::condition_variable cv; 41 T value{}; 42 43 std::function<void(const T &t)> onComplete = nullptr; 44 }; 45 46 template<class T> Promise(const T & t)47Promise<T>::Promise(const T& t) 48 { 49 value = t; 50 resolved = true; 51 } 52 53 template<class T> IsResolved()54bool Promise<T>::IsResolved() const 55 { 56 return resolved; 57 } 58 59 template<class T> Await()60const T &Promise<T>::Await() 61 { 62 if (resolved == false) { 63 std::unique_lock<std::mutex> lock(mutex); 64 cv.wait(lock, [this]() { return resolved == true; }); 65 } 66 return value; 67 } 68 69 template<class T> Then(std::function<void (const T & t)> func)70void Promise<T>::Then(std::function<void(const T &t)> func) 71 { 72 std::unique_lock<std::mutex> lock(mutex); 73 if (resolved == false) { 74 onComplete = func; 75 } else { 76 func(value); 77 } 78 } 79 80 template<class T> Resolve(const T & t)81bool Promise<T>::Resolve(const T &t) 82 { 83 if (resolved == false) { 84 std::unique_lock<std::mutex> lock(mutex); 85 if (resolved == false) { 86 value = t; 87 resolved = true; 88 cv.notify_all(); 89 if (onComplete != nullptr) { 90 onComplete(value); 91 } 92 return true; 93 } 94 } 95 return false; 96 } 97 } // namespace OHOS 98 99 #endif // UTILS_INCLUDE_PROMISE_H 100