diff third_party/libuv/docs/code/progress/main.c @ 160:948de3f54cea

[ThirdParty] Added libuv
author June Park <parkjune1995@gmail.com>
date Wed, 14 Jan 2026 19:39:52 -0800
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/third_party/libuv/docs/code/progress/main.c	Wed Jan 14 19:39:52 2026 -0800
@@ -0,0 +1,47 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include <uv.h>
+
+uv_loop_t *loop;
+uv_async_t async;
+
+double percentage;
+
+void fake_download(uv_work_t *req) {
+    int size = *((int*) req->data);
+    int downloaded = 0;
+    while (downloaded < size) {
+        percentage = downloaded*100.0/size;
+        async.data = (void*) &percentage;
+        uv_async_send(&async);
+
+        sleep(1);
+        downloaded += (200+random())%1000; // can only download max 1000bytes/sec,
+                                           // but at least a 200;
+    }
+}
+
+void after(uv_work_t *req, int status) {
+    fprintf(stderr, "Download complete\n");
+    uv_close((uv_handle_t*) &async, NULL);
+}
+
+void print_progress(uv_async_t *handle) {
+    double percentage = *((double*) handle->data);
+    fprintf(stderr, "Downloaded %.2f%%\n", percentage);
+}
+
+int main() {
+    loop = uv_default_loop();
+
+    uv_work_t req;
+    int size = 10240;
+    req.data = (void*) &size;
+
+    uv_async_init(loop, &async, print_progress);
+    uv_queue_work(loop, &req, fake_download, after);
+
+    return uv_run(loop, UV_RUN_DEFAULT);
+}