Created
May 2, 2018 12:27
-
-
Save Enchufa2/bf6bb2754bc57d3b4c60f171f6e25252 to your computer and use it in GitHub Desktop.
Very simple 'yield' demo in C for DES
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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