xref: /netbsd-src/external/mit/libuv/dist/docs/code/progress/main.c (revision 0e552da7216834a96e91ad098e59272b41087480)
1*0e552da7Schristos #include <stdio.h>
2*0e552da7Schristos #include <stdlib.h>
3*0e552da7Schristos #include <unistd.h>
4*0e552da7Schristos 
5*0e552da7Schristos #include <uv.h>
6*0e552da7Schristos 
7*0e552da7Schristos uv_loop_t *loop;
8*0e552da7Schristos uv_async_t async;
9*0e552da7Schristos 
10*0e552da7Schristos double percentage;
11*0e552da7Schristos 
fake_download(uv_work_t * req)12*0e552da7Schristos void fake_download(uv_work_t *req) {
13*0e552da7Schristos     int size = *((int*) req->data);
14*0e552da7Schristos     int downloaded = 0;
15*0e552da7Schristos     while (downloaded < size) {
16*0e552da7Schristos         percentage = downloaded*100.0/size;
17*0e552da7Schristos         async.data = (void*) &percentage;
18*0e552da7Schristos         uv_async_send(&async);
19*0e552da7Schristos 
20*0e552da7Schristos         sleep(1);
21*0e552da7Schristos         downloaded += (200+random())%1000; // can only download max 1000bytes/sec,
22*0e552da7Schristos                                            // but at least a 200;
23*0e552da7Schristos     }
24*0e552da7Schristos }
25*0e552da7Schristos 
after(uv_work_t * req,int status)26*0e552da7Schristos void after(uv_work_t *req, int status) {
27*0e552da7Schristos     fprintf(stderr, "Download complete\n");
28*0e552da7Schristos     uv_close((uv_handle_t*) &async, NULL);
29*0e552da7Schristos }
30*0e552da7Schristos 
print_progress(uv_async_t * handle)31*0e552da7Schristos void print_progress(uv_async_t *handle) {
32*0e552da7Schristos     double percentage = *((double*) handle->data);
33*0e552da7Schristos     fprintf(stderr, "Downloaded %.2f%%\n", percentage);
34*0e552da7Schristos }
35*0e552da7Schristos 
main()36*0e552da7Schristos int main() {
37*0e552da7Schristos     loop = uv_default_loop();
38*0e552da7Schristos 
39*0e552da7Schristos     uv_work_t req;
40*0e552da7Schristos     int size = 10240;
41*0e552da7Schristos     req.data = (void*) &size;
42*0e552da7Schristos 
43*0e552da7Schristos     uv_async_init(loop, &async, print_progress);
44*0e552da7Schristos     uv_queue_work(loop, &req, fake_download, after);
45*0e552da7Schristos 
46*0e552da7Schristos     return uv_run(loop, UV_RUN_DEFAULT);
47*0e552da7Schristos }
48