1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4
5 #include <uv.h>
6
7 #define FIB_UNTIL 25
8 uv_loop_t *loop;
9
fib_(long t)10 long fib_(long t) {
11 if (t == 0 || t == 1)
12 return 1;
13 else
14 return fib_(t-1) + fib_(t-2);
15 }
16
fib(uv_work_t * req)17 void fib(uv_work_t *req) {
18 int n = *(int *) req->data;
19 if (random() % 2)
20 sleep(1);
21 else
22 sleep(3);
23 long fib = fib_(n);
24 fprintf(stderr, "%dth fibonacci is %lu\n", n, fib);
25 }
26
after_fib(uv_work_t * req,int status)27 void after_fib(uv_work_t *req, int status) {
28 fprintf(stderr, "Done calculating %dth fibonacci\n", *(int *) req->data);
29 }
30
main()31 int main() {
32 loop = uv_default_loop();
33
34 int data[FIB_UNTIL];
35 uv_work_t req[FIB_UNTIL];
36 int i;
37 for (i = 0; i < FIB_UNTIL; i++) {
38 data[i] = i;
39 req[i].data = (void *) &data[i];
40 uv_queue_work(loop, &req[i], fib, after_fib);
41 }
42
43 return uv_run(loop, UV_RUN_DEFAULT);
44 }
45