Created
April 8, 2013 23:54
worker 内で単一の async ハンドラを操作すると thread safe なのかチェックするテスト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> ./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