doc: fix threading bugs in progress example

Fixes #4386

Fixed race conditions and memory safety issues in the progress example
by using C11 atomic operations for proper thread synchronization.

Changes:
- Changed percentage from double to _Atomic double
- Use atomic_store_explicit() with memory_order_release when writing
- Use atomic_load_explicit() with memory_order_acquire when reading
- Removed unsafe pointer passing via async.data

This ensures proper memory synchronization between the worker thread
and async callback, preventing data races and dangling pointer issues.
This commit is contained in:
Bitshifter-9 2025-12-02 15:07:51 +05:30
parent bf44c3fdcc
commit e637d36d97

View File

@ -1,3 +1,4 @@
#include <stdatomic.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
@ -7,41 +8,42 @@
uv_loop_t *loop; uv_loop_t *loop;
uv_async_t async; uv_async_t async;
double percentage; _Atomic double percentage;
void fake_download(uv_work_t *req) { void fake_download(uv_work_t *req) {
int size = *((int*) req->data); int size = *((int *)req->data);
int downloaded = 0; int downloaded = 0;
while (downloaded < size) { double pct;
percentage = downloaded*100.0/size; while (downloaded < size) {
async.data = (void*) &percentage; pct = downloaded * 100.0 / size;
uv_async_send(&async); atomic_store_explicit(&percentage, pct, memory_order_release);
uv_async_send(&async);
sleep(1); sleep(1);
downloaded += (200+random())%1000; // can only download max 1000bytes/sec, downloaded += (200 + random()) % 1000; // can only download max
// but at least a 200; // 1000bytes/sec, but at least a 200;
} }
} }
void after(uv_work_t *req, int status) { void after(uv_work_t *req, int status) {
fprintf(stderr, "Download complete\n"); fprintf(stderr, "Download complete\n");
uv_close((uv_handle_t*) &async, NULL); uv_close((uv_handle_t *)&async, NULL);
} }
void print_progress(uv_async_t *handle) { void print_progress(uv_async_t *handle) {
double percentage = *((double*) handle->data); double pct = atomic_load_explicit(&percentage, memory_order_acquire);
fprintf(stderr, "Downloaded %.2f%%\n", percentage); fprintf(stderr, "Downloaded %.2f%%\n", pct);
} }
int main() { int main() {
loop = uv_default_loop(); loop = uv_default_loop();
uv_work_t req; uv_work_t req;
int size = 10240; int size = 10240;
req.data = (void*) &size; req.data = (void *)&size;
uv_async_init(loop, &async, print_progress); uv_async_init(loop, &async, print_progress);
uv_queue_work(loop, &req, fake_download, after); uv_queue_work(loop, &req, fake_download, after);
return uv_run(loop, UV_RUN_DEFAULT); return uv_run(loop, UV_RUN_DEFAULT);
} }