Skip to content

Commit e75fae5

Browse files
committed
[fibers] Query condition before and after yield
1 parent 3c039d9 commit e75fae5

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

src/modm/processing/fiber/functions.hpp

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,8 @@ yield();
5353
modm::fiber::id
5454
get_id();
5555

56-
/// Yields the current fiber until `bool condition()` returns true.
56+
/// Yields the current fiber while `bool condition()` returns true.
57+
/// @warning If `bool condition()` is true on first call, no yield is performed!
5758
template< class Function >
5859
requires requires { std::is_invocable_r_v<bool, Function, void>; }
5960
void
@@ -67,6 +68,8 @@ poll(Function &&condition)
6768
* Yields the current fiber until `bool condition()` returns true or the time
6869
* duration has elapsed.
6970
*
71+
* @warning If `bool condition()` is true on first call, no yield is performed!
72+
*
7073
* @returns `true` if the condition was met, `false` if the time duration has
7174
* elapsed.
7275
*
@@ -79,6 +82,8 @@ requires requires { std::is_invocable_r_v<bool, Function, void>; }
7982
bool
8083
poll_for(std::chrono::duration<Rep, Period> sleep_duration, Function &&condition)
8184
{
85+
if (std::forward<Function>(condition)()) return true;
86+
8287
// Only choose the microsecond clock if necessary
8388
using Clock = std::conditional_t<
8489
std::is_convertible_v<std::chrono::duration<Rep, Period>,
@@ -87,8 +92,8 @@ poll_for(std::chrono::duration<Rep, Period> sleep_duration, Function &&condition
8792

8893
const auto start = Clock::now();
8994
do {
90-
if (std::forward<Function>(condition)()) return true;
9195
modm::this_fiber::yield();
96+
if (std::forward<Function>(condition)()) return true;
9297
}
9398
while((Clock::now() - start) <= sleep_duration);
9499
return false;
@@ -98,6 +103,8 @@ poll_for(std::chrono::duration<Rep, Period> sleep_duration, Function &&condition
98103
* Yields the current fiber until `bool condition()` returns true or the sleep
99104
* time has been reached.
100105
*
106+
* @warning If `bool condition()` is true on first call, no yield is performed!
107+
*
101108
* @returns `true` if the condition was met, `false` if the sleep time has
102109
* elapsed.
103110
*
@@ -110,11 +117,13 @@ requires requires { std::is_invocable_r_v<bool, Function, void>; }
110117
bool
111118
poll_until(std::chrono::time_point<Clock, Duration> sleep_time, Function &&condition)
112119
{
120+
if (std::forward<Function>(condition)()) return true;
121+
113122
const auto start = Clock::now();
114123
const auto sleep_duration = sleep_time - start;
115124
do {
116-
if (std::forward<Function>(condition)()) return true;
117125
modm::this_fiber::yield();
126+
if (std::forward<Function>(condition)()) return true;
118127
}
119128
while((Clock::now() - start) <= sleep_duration);
120129
return false;

0 commit comments

Comments
 (0)