Skip to content

Instantly share code, notes, and snippets.

@Enchufa2
Created May 2, 2018 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Enchufa2/bf6bb2754bc57d3b4c60f171f6e25252 to your computer and use it in GitHub Desktop.
Save Enchufa2/bf6bb2754bc57d3b4c60f171f6e25252 to your computer and use it in GitHub Desktop.
Very simple 'yield' demo in C for DES
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
#include <math.h>
#include <time.h>
typedef struct process {
double *now;
double (*run)(struct process *);
jmp_buf buf;
} process_t;
#define YIELD(t) self->run = &reentry; if (!setjmp(self->buf)) return t;
double reentry(process_t *self) { longjmp(self->buf, 1); }
double rexp(double lambda);
double customer(process_t *self) {
printf("customer started at: %.3f\n", *self->now);
YIELD(rexp(1));
printf("customer finished at: %.3f\n", *self->now);
return -1;
}
int main(int argc, char *argv[]) {
double now = 0, delay;
process_t process = { &now, &customer };
srand((unsigned)time(NULL));
while ((delay = process.run(&process)) >= 0)
now += delay;
return 0;
}
double rexp(double lambda) {
double u = rand() / (RAND_MAX + 1.0);
return -log(1.0 - u) / lambda;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment