Skip to content

Instantly share code, notes, and snippets.

@shigeki
Created April 10, 2013 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shigeki/5351299 to your computer and use it in GitHub Desktop.
Save shigeki/5351299 to your computer and use it in GitHub Desktop.
uv_check() を利用した thread worker からのメッセージの出力 (worker 内の sleep 処理に依存しない方法)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <queue>
#include "uv.h"
using namespace std;
uv_loop_t *loop;
static int check_called = 0;
static int worker_finished = 0;
static queue<char*> g_msgQueue;
static uv_mutex_t g_mutex;
static int g_line_count = 0;
const int WORKER_MAX = 10;
void print_progress(uv_check_t *handle, int status /*UNUSED*/) {
check_called++;
uv_mutex_lock(&g_mutex);
while ( !g_msgQueue.empty()) {
char* msg = g_msgQueue.front();
g_msgQueue.pop();
fprintf(stderr, "%2d: check_called=%3d, thread=%lud: %s\n",
++g_line_count, check_called, uv_thread_self(), msg);
// fflush( stderr);
free(msg);
}
uv_mutex_unlock(&g_mutex);
}
void fake_download0(uv_work_t *req) {
int size = *((int*) req->data);
const int MSG_SIZE = 256;
double percentage;
int downloaded = 0;
int send_count = 0;
while (downloaded < size) {
send_count++;
percentage = downloaded*100.0/size;
char* msg = (char*)malloc( MSG_SIZE);
sprintf(msg, "from=%lud(send_count=%d) Downloaded %.2f%%", uv_thread_self(), send_count, percentage);
uv_mutex_lock(&g_mutex);
g_msgQueue.push(msg);
uv_mutex_unlock(&g_mutex);
downloaded++;
}
req->data = (void*) &downloaded;
}
void after0(uv_work_t *req, int status) {
int downloaded = *((int*) req->data);
fprintf(stderr, "%2d: worker_finished=%3d, thread=%lud: after()\n",
++g_line_count, ++worker_finished, uv_thread_self());
}
int main() {
loop = uv_default_loop();
int size = 5;
uv_work_t req[ WORKER_MAX];
uv_check_t check;
uv_check_init(loop, &check);
uv_check_start(&check, print_progress);
uv_unref((uv_handle_t *)&check);
uv_mutex_init(&g_mutex);
fprintf(stderr, "%2d: worker_finished=%3d, thread=%lud: %s\n",
++g_line_count, worker_finished, uv_thread_self(), "main() start");
for ( int i = 0; i < WORKER_MAX; i++) {
req[ i].data = (void*) &size;
uv_queue_work(loop, req+i, fake_download0, after0);
}
uv_run(loop, UV_RUN_DEFAULT);
fprintf(stderr, "%2d: worker_finished=%3d, thread=%lud: %s\n",
++g_line_count, worker_finished, uv_thread_self(), "main() end");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment