Skip to content

Commit 7762867

Browse files
[Concurrency] Support duration-based sleep in cooperative executor
1 parent 3619472 commit 7762867

File tree

1 file changed

+37
-14
lines changed

1 file changed

+37
-14
lines changed

stdlib/public/Concurrency/CooperativeGlobalExecutor.inc

Lines changed: 37 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,13 @@
2626
#include <thread>
2727
#include "swift/Basic/ListMerger.h"
2828

29+
#if __has_include(<time.h>)
30+
# include <time.h>
31+
#endif
32+
#ifndef NSEC_PER_SEC
33+
# define NSEC_PER_SEC 1000000000ull
34+
#endif
35+
2936
namespace {
3037

3138
struct JobQueueTraits {
@@ -108,17 +115,7 @@ static void swift_task_enqueueMainExecutorImpl(Job *job) {
108115
swift_task_enqueueGlobalImpl(job);
109116
}
110117

111-
/// Insert a job into the cooperative global queue with a delay.
112-
SWIFT_CC(swift)
113-
static void swift_task_enqueueGlobalWithDelayImpl(JobDelay delay,
114-
Job *newJob) {
115-
assert(newJob && "no job provided");
116-
117-
auto deadline = std::chrono::steady_clock::now()
118-
+ std::chrono::duration_cast<JobDeadline::duration>(
119-
std::chrono::nanoseconds(delay));
120-
JobDeadlineStorage<>::set(newJob, deadline);
121-
118+
static void insertDelayedJob(Job *newJob, JobDeadline deadline) {
122119
Job **position = &DelayedJobQueue;
123120
while (auto cur = *position) {
124121
// If we find a job with a later deadline, insert here.
@@ -136,14 +133,40 @@ static void swift_task_enqueueGlobalWithDelayImpl(JobDelay delay,
136133
*position = newJob;
137134
}
138135

136+
/// Insert a job into the cooperative global queue with a delay.
137+
SWIFT_CC(swift)
138+
static void swift_task_enqueueGlobalWithDelayImpl(JobDelay delay,
139+
Job *newJob) {
140+
assert(newJob && "no job provided");
141+
142+
auto deadline = std::chrono::steady_clock::now()
143+
+ std::chrono::duration_cast<JobDeadline::duration>(
144+
std::chrono::nanoseconds(delay));
145+
JobDeadlineStorage<>::set(newJob, deadline);
146+
147+
insertDelayedJob(newJob, deadline);
148+
}
149+
139150
SWIFT_CC(swift)
140151
static void swift_task_enqueueGlobalWithDeadlineImpl(long long sec,
141152
long long nsec,
142153
long long tsec,
143154
long long tnsec,
144-
int clock, Job *job) {
145-
assert(job && "no job provided");
146-
// TODO: implementation
155+
int clock, Job *newJob) {
156+
assert(newJob && "no job provided");
157+
158+
long long nowSec;
159+
long long nowNsec;
160+
swift_get_time(&nowSec, &nowNsec, (swift_clock_id)clock);
161+
162+
uint64_t delta = (sec - nowSec) * NSEC_PER_SEC + nsec - nowNsec;
163+
164+
auto deadline = std::chrono::steady_clock::now()
165+
+ std::chrono::duration_cast<JobDeadline::duration>(
166+
std::chrono::nanoseconds(delta));
167+
JobDeadlineStorage<>::set(newJob, deadline);
168+
169+
insertDelayedJob(newJob, deadline);
147170
}
148171

149172
/// Recognize jobs in the delayed-jobs queue that are ready to execute

0 commit comments

Comments
 (0)