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