/**************************************************
* Module initialization
**************************************************/
uv_loop_t *second_threaded_loop;
void create_loop(void *)
{
uv_run(second_threaded_loop, UV_RUN_DEFAULT);
}
void init (Handle<Object> target)
{
NanScope();
uv_thread_t thread_loop;
uv_async_t async;
second_threaded_loop = uv_loop_new();
// Reference the second loop so it keeps on idle
uv_async_init(second_threaded_loop, &async, NULL);
uv_thread_create(&thread_loop, create_loop, NULL);
// ....
}
/**************************************************
* Then, a random function running on
* the main loop does
**************************************************/
NAN_METHOD(Foo::doHeavyOperation)
{
// ...
uv_work_t* req = new uv_work_t;
random_context_struct *ctx = new random_context_struct;
// ctx->handle is a Handle<Object>
ctx->handle = Persistent<Object>::New(args.This());
req->data = /* random context */;
uv_queue_work(second_threaded_loop, req, startHeavyOpeation, EmitMessage);
// ....
NanReturnUndefined();
}
/**************************************************
* After startHeavyOpeation ends, Emit Message is called
* Where it supossly should emit an event
* informing that the task finished
**************************************************/
void EmitMessage(uv_work_t *req, int status)
{
random_context_struct *ctx = (random_context_struct*)req->data;
Local<Value> argv[1] = { NanSymbol("parsed") };
TryCatch tc;
MakeCallback(ctx->handle, "done", 1, argv);
if (tc.HasCaught())
printf("Error occured");
}
Now, if I run this task on the main event loop the operation succeeds and the event is triggered,
but in the second loop the application prematurely ends, without any explicit error being thrown, or being caught.
A second loop to me seems the best idea, because blocking in the main event loop is not be acceptable as the server
will be receiving new connections from other users. Creating a thread for each request would not be acceptable too,
as the overhead would be unmanageable. A second event loop on a child thread seems a reasonably approach but emitting seems not to be possible.