Skip to content

How to check if server is running successfully in another thread? #1548

Closed
@jimmy-park

Description

@jimmy-park

We can't stop server immediately before server is calling listen(). So we have to check using is_running().

Server server;
auto t = thread([&]() { server.listen(HOST, PORT); });

while (!server.is_running())
    std::this_thread::sleep_for(std::chrono::milliseconds{10});

server.stop();
t.join();

However, this example has a problem because bind() or listen() could be failed before is_running(). The program may get stuck in a while loop. To prevent this, I need to add a flag.

std::atomic_bool done { false };
Server server;
auto t = thread([&]() { 
    server.listen(HOST, PORT);
    done = true;
});

while (!server.is_running() && !done)
    std::this_thread::sleep_for(std::chrono::milliseconds{10});

server.stop();
t.join();

Is this the correct way to use Server class? Or is there a better way to check the server?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions