Skip to content

Instantly share code, notes, and snippets.

@shigeki
Created April 8, 2013 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shigeki/5341670 to your computer and use it in GitHub Desktop.
Save shigeki/5341670 to your computer and use it in GitHub Desktop.
worker 内で単一の async ハンドラを操作すると thread safe なのかチェックするテスト
#include <stdio.h>
#include <stdlib.h>
#include "uv.h"
uv_loop_t *loop;
uv_async_t async;
static int closed = 0;
static int async_called = 0;
void print_progress(uv_async_t *handle, int status /*UNUSED*/) {
char *msg;
msg = (char*) handle->data;
async_called++;
// fprintf(stderr, "%s", msg);
}
void fake_download0(uv_work_t *req) {
int size = *((int*) req->data);
char msg[256];
double percentage;
int downloaded = 0;
while (downloaded < size) {
percentage = downloaded*100.0/size;
sprintf(msg, "#0 Downloaded %.2f%%\n", percentage);
async.data = (void*) &msg;
uv_async_send(&async);
downloaded++;
}
req->data = (void*) &downloaded;
}
void after0(uv_work_t *req, int status) {
int downloaded = *((int*) req->data);
closed++;
fprintf(stderr, "#0 Download complete. async_send: %d\n", downloaded);
if (closed == 1) {
uv_close((uv_handle_t*) &async, NULL);
}
}
void fake_download1(uv_work_t *req) {
int size = *((int*) req->data);
char msg[256];
double percentage;
int downloaded = 0;
while (downloaded < size) {
percentage = downloaded*100.0/size;
sprintf(msg, "#1 Downloaded %.2f%%\n", percentage);
async.data = (void*) &msg;
uv_async_send(&async);
downloaded++;
}
req->data = (void*) &downloaded;
}
void after1(uv_work_t *req, int status) {
int downloaded = *((int*) req->data);
closed++;
fprintf(stderr, "#1 Download complete. async_send: %d\n", downloaded);
if (closed == 1) {
uv_close((uv_handle_t*) &async, NULL);
}
}
int main() {
loop = uv_default_loop();
int size = 10240;
uv_work_t req[2];
uv_async_init(loop, &async, print_progress);
req[0].data = (void*) &size;
req[1].data = (void*) &size;
uv_queue_work(loop, req, fake_download0, after0);
uv_queue_work(loop, req + 1, fake_download1, after1);
uv_run(loop, UV_RUN_DEFAULT);
fprintf(stderr, "async_called: %d\n", async_called);
}
> ./worker-test
#0 Download complete. async_send: 10240
#1 Download complete. async_send: 10240
async_called: 183
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment