1 /*
2  * Copyright (c) 2024 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 RECORD_CONDITION_VARIABLE_H
17 #define RECORD_CONDITION_VARIABLE_H
18 
19 #include "cpp/condition_variable.h"
20 #include "sync/record_mutex.h"
21 
22 namespace ffrt {
23 class RecordConditionVariable {
24 public:
25     template <typename Rep, typename Period>
26     cv_status WaitFor(std::unique_lock<RecordMutex>& lk, const std::chrono::duration<Rep, Period>& sleep_time) noexcept
27     {
28         timespec ts;
29         std::chrono::nanoseconds ns = std::chrono::steady_clock::now().time_since_epoch();
30         ns += std::chrono::duration_cast<std::chrono::nanoseconds>(sleep_time);
31         ts.tv_sec = std::chrono::duration_cast<std::chrono::seconds>(ns).count();
32         ns -= std::chrono::seconds(ts.tv_sec);
33         ts.tv_nsec = static_cast<long>(ns.count());
34 
35         auto ret = ffrt_cond_timedwait(&cv_, lk.mutex()->GetMutex(), &ts);
36         if (ret == ffrt_success) {
37             return cv_status::no_timeout;
38         }
39         return cv_status::timeout;
40     }
41 
42     void NotifyOne() noexcept
43     {
44         cv_.notify_one();
45     }
46 
47     void NotifyAll() noexcept
48     {
49         cv_.notify_all();
50     }
51 
52 private:
53     ffrt::condition_variable cv_;
54 };
55 } // namespace ffrt
56 
57 #endif