Skip to content

Commit

Permalink
sleep
Browse files Browse the repository at this point in the history
  • Loading branch information
vityaman committed Nov 21, 2024
1 parent 3d41590 commit df19736
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 14 deletions.
7 changes: 0 additions & 7 deletions source/coroed/api/clock.h

This file was deleted.

10 changes: 6 additions & 4 deletions source/coroed/api/clock.c → source/coroed/api/sleep.c
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
#include "clock.h"
#include "sleep.h"

#include <assert.h>
#include <bits/time.h>
#include <stdint.h>
#include <time.h>

#include "coroed/api/task.h"

static unsigned long long timespec2ms(const struct timespec* spec) {
const time_t ms_in_s = 1000;
return (unsigned long long)spec->tv_sec * ms_in_s + spec->tv_sec / (ms_in_s * ms_in_s);
}

uint64_t clock_now() {
static uint64_t clock_now() {
struct timespec spec;

int code = clock_gettime(CLOCK_MONOTONIC, &spec);
Expand All @@ -19,9 +21,9 @@ uint64_t clock_now() {
return timespec2ms(&spec);
}

void clock_delay(uint64_t milliseconds) {
void task_sleep(struct task* caller, uint64_t milliseconds) {
const unsigned long long start = clock_now();
while (clock_now() - start < milliseconds) {
// Do nothing
task_yield(caller);
}
}
9 changes: 9 additions & 0 deletions source/coroed/api/sleep.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#pragma once

#include <stdint.h>

#include "task.h"

#define SLEEP(ms) task_sleep(__self, (ms))

void task_sleep(struct task* caller, uint64_t milliseconds);
6 changes: 3 additions & 3 deletions source/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
#include <string.h>
#include <unistd.h>

#include "coroed/api/clock.h"
#include "coroed/api/event.h"
#include "coroed/api/log.h"
#include "coroed/api/sleep.h"
#include "coroed/api/task.h"

enum {
Expand All @@ -25,7 +25,7 @@ static atomic_int_least64_t state = 0;
static struct event event;

TASK_DEFINE(eventer, void, ignored) {
sleep(1);
SLEEP(1000);
state = 1;
event_fire(&event);
}
Expand Down Expand Up @@ -69,7 +69,7 @@ TASK_DEFINE(print_loop, const char, message) {
YIELD;

free(msg);
clock_delay(delay);
SLEEP(delay);
}
}

Expand Down

0 comments on commit df19736

Please sign in to comment.