Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add waitFor to djinni::Future #175

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 25 additions & 8 deletions support-lib/cpp/Future.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -271,16 +271,15 @@ class Future {
std::unique_lock lk(sharedState->mutex);
return sharedState->isReady();
}
// wait until future becomes `isReady()` or the timeout elapses
// returns true if the future is ready, false if the timeout elapsed
template<typename Rep, typename Period>
bool waitFor(std::chrono::duration<Rep, Period> duration) const {
return waitImpl(std::make_optional(std::chrono::steady_clock::now() + duration));
}
// wait until future becomes `isReady()`
void wait() const {
auto sharedState = std::atomic_load(&_sharedState);
assert(sharedState); // call on invalid future will trigger assertion
std::unique_lock lk(sharedState->mutex);
#if defined(__EMSCRIPTEN__)
assert(sharedState->isReady()); // in wasm we must not block and wait
#else
sharedState->cv.wait(lk, [state = sharedState] {return state->isReady();});
#endif
waitImpl({});
}
// wait until future becomes `isReady()` and return the result. This can
// only be called once.
Expand Down Expand Up @@ -343,6 +342,24 @@ class Future {

private:
detail::SharedStatePtr<T> _sharedState;

template<typename Clock = std::chrono::steady_clock, typename Duration = std::chrono::steady_clock::duration>
bool waitImpl(std::optional<std::chrono::time_point<Clock, Duration>> deadline) const {
auto sharedState = std::atomic_load(&_sharedState);
assert(sharedState); // call on invalid future will trigger assertion
std::unique_lock lk(sharedState->mutex);
#if defined(__EMSCRIPTEN__)
assert(sharedState->isReady()); // in wasm we must not block and wait
#else
auto predicate = [&sharedState] {return sharedState->isReady();};
if (deadline) {
return sharedState->cv.wait_until(lk, *deadline, std::move(predicate));
} else {
sharedState->cv.wait(lk, std::move(predicate));
return true;
}
#endif
}

#if defined(DJINNI_FUTURE_HAS_COROUTINE_SUPPORT)
public:
Expand Down
Loading