Skip to content

[wasm][stdlib] Don't use <thread> sleep API with swift-threading-package=none #69006

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

Merged
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
26 changes: 24 additions & 2 deletions stdlib/public/Concurrency/CooperativeGlobalExecutor.inc
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@
///===------------------------------------------------------------------===///

#include <chrono>
#include <thread>
#ifndef SWIFT_THREADING_NONE
# include <thread>
#endif
#include <errno.h>
#include "swift/Basic/ListMerger.h"

#if __has_include(<time.h>)
Expand Down Expand Up @@ -195,6 +198,25 @@ static void recognizeReadyDelayedJobs() {
DelayedJobQueue = nextDelayedJob;
}

static void sleepThisThreadUntil(JobDeadline deadline) {
#ifdef SWIFT_THREADING_NONE
auto duration = deadline - std::chrono::steady_clock::now();
// If the deadline is in the past, don't sleep with invalid negative value
if (duration <= std::chrono::nanoseconds::zero()) {
return;
}
auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration);
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(duration - sec);

struct timespec ts;
ts.tv_sec = sec.count();
ts.tv_nsec = ns.count();
while (nanosleep(&ts, &ts) == -1 && errno == EINTR);
#else
std::this_thread::sleep_until(deadline);
#endif
}

/// Claim the next job from the cooperative global queue.
static Job *claimNextFromCooperativeGlobalQueue() {
while (true) {
Expand All @@ -211,7 +233,7 @@ static Job *claimNextFromCooperativeGlobalQueue() {
// TODO: should the donator have some say in this?
if (auto delayedJob = DelayedJobQueue) {
auto deadline = JobDeadlineStorage<>::get(delayedJob);
std::this_thread::sleep_until(deadline);
sleepThisThreadUntil(deadline);
continue;
}

Expand Down