Skip to content

Instantly share code, notes, and snippets.

@Enchufa2
Created May 2, 2018
Embed
What would you like to do?
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