Stiffstream / restinio

Cross-platform, efficient, customizable, and robust asynchronous HTTP(S)/WebSocket server C++ library with the right balance between performance and ease of use
Other
1.15k stars 93 forks source link

Simple thread server #87

Closed dyfet closed 4 years ago

dyfet commented 4 years ago

Right now it is very simple to create a restinio server from "main" that exits with sigint (or break event on windows?).

int main() {
    restinio::run(
        restinio::on_this_thread()
        .port(8080)
        .address("localhost")
        .request_handler([](auto req) {
            return req->create_response().set_body("Hello, World!").done();
        }));

However, a very common use case would be to create a seperate thread to run the server, and without signal handling. Being able to start or stop the http service under application control is also important. The near equivalent requires creating an asio context, an http_server_t, etc, just to be able to get async start and stop. It can be a lot of boilerplate code.

It would be nice if there was a way to create an asyncStart/Stop managed instance with some of this same simplicity as the generic example so that it is easy to start and stop it, and have it run on it's own thread (or thread pool) without all the extra boilerplate code or sigint handler.

eao197 commented 4 years ago

Thanks for proposing this. I think it could be a good addition to RESTinio's toolbox in v.0.6.7 or v.0.6.8.

eao197 commented 4 years ago

A new helper function run_async will be a part of v.0.6.7. It allows to run HTTP-server that way:

auto server = restinio::run_async(
   restinio::own_io_context(),
   restinio::server_settings_t{}.address(...).port(...).request_handler(...),
   4);
... // Some other actions on the current thread that is not blocked. 
    // HTTP-server will be automatically stopped when `server` goes out of scope.

run_async starts an HTTP-server on a bunch of new threads (the size of that bunch is specified as a parameter to run_async) and returns the control to the caller as soon as HTTP-server started.

This asynchronously running HTTP-server can be stopped manually:

auto server = restinio::run_async(...);
... // Some other actions on the current thread.
server->stop(); // Shutdown signal is sent to HTTP-server.
server->wait(); // Wait while HTTP-server will be stopped.
dyfet commented 4 years ago

That's perfect! I can isolate my signal handlers to my main thread, and I can manage the server instance(s) from it.

eao197 commented 4 years ago

I close this issue because run_async is available since v.0.6.7.