main.c 1.1 KB

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