• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 /**
17  * @addtogroup FFRT
18  * @{
19  *
20  * @brief Provides FFRT C++ APIs.
21  *
22  * @since 10
23  */
24 
25 /**
26  * @file sleep.h
27  *
28  * @brief Declares the sleep and yield interfaces in C++.
29  *
30  * @library libffrt.z.so
31  * @kit FunctionFlowRuntimeKit
32  * @syscap SystemCapability.Resourceschedule.Ffrt.Core
33  * @since 10
34  */
35 
36 #ifndef FFRT_API_CPP_SLEEP_H
37 #define FFRT_API_CPP_SLEEP_H
38 
39 #include <chrono>
40 #include "c/sleep.h"
41 
42 namespace ffrt {
43 /**
44  * @namespace ffrt::this_task
45  * @brief Contains utility functions for the currently executing task.
46  */
47 namespace this_task {
48 /**
49  * @brief Yields the execution of the current task.
50  *
51  * This function allows other tasks or threads to be scheduled by yielding the current task's execution.
52  *
53  * @since 10
54  */
yield()55 static inline void yield()
56 {
57     ffrt_yield();
58 }
59 
60 /**
61  * @brief Suspends the current task for a specified duration.
62  *
63  * @tparam _Rep The type of the representation of the duration (e.g., int or long).
64  * @tparam _Period The period of the duration (e.g., milliseconds, microseconds).
65  * @param d The duration for which the task should be suspended.
66  * @since 10
67  */
68 template <class _Rep, class _Period>
sleep_for(const std::chrono::duration<_Rep,_Period> & d)69 inline void sleep_for(const std::chrono::duration<_Rep, _Period>& d)
70 {
71     ffrt_usleep(std::chrono::duration_cast<std::chrono::microseconds>(d).count());
72 }
73 
74 
75 /**
76  * @brief Suspends the current task until a specific time point.
77  *
78  * @tparam _Clock The clock type that provides the time point (e.g., steady_clock).
79  * @tparam _Duration The duration type for the time point.
80  * @param abs_time The absolute time point at which the task should resume.
81  * @since 10
82  */
83 template<class _Clock, class _Duration>
sleep_until(const std::chrono::time_point<_Clock,_Duration> & abs_time)84 inline void sleep_until(
85     const std::chrono::time_point<_Clock, _Duration>& abs_time)
86 {
87     sleep_for(abs_time.time_since_epoch() - _Clock::now().time_since_epoch());
88 }
89 } // namespace this_task
90 } // namespace ffrt
91 
92 #endif // FFRT_API_CPP_SLEEP_H
93 /** @} */