-
Notifications
You must be signed in to change notification settings - Fork 93
Using event loop
Dmitry edited this page Dec 2, 2016
·
2 revisions
It's possible to perform heavy operations from another thread and perform response asynchronously. For this event loop is introduced.
Please note, to make posting tasks from another thread possible, ngrest must be compiled with option
WITH_THREAD_LOCK=1
. You must have this environment variable when you installing ngrest.
Currently event loop is only supported with simple ngrest server.
Long synchronous operation can be performed without blocking event look like that:
#include <chrono>
#include <thread>
void ExampleService::echoASync(const std::string& value, ngrest::Callback<const std::string&>& callback)
{
// take callback by reference because it's allocated in mempool
// take argument(s) by value because it's allocated in stack
std::thread([&callback, value]{
// perform some long synchronous operation
std::this_thread::sleep_for(std::chrono::seconds(1));
// post to event loop
Handler::post([&callback, value]{
// this will be executed from main thread
callback.success("You said " + value);
});
})
.detach();
}
Please note, you must take arguments by value and callback by reference else UB may occur.