-2

I have the following method on a class

void Listener::Start()
{
    Logger logger;
    std::string logMessage("Starting '" + to_utf8string(GetName()) + "' Listener");
    http_listener httpListener(GetUri());
    std::string listenerName(to_utf8string(name));

    logger.log(logMessage);

    // listener recieves a GET request.
    httpListener.support(methods::GET, [listenerName](http_request request)
    {
        Logger logger;
        std::string logMessage("GET request recieved from " + listenerName);

        logger.log(logMessage);

        // dummy line just till routing is dealt with
        request.reply(status_codes::OK, logMessage);

    });

    // open listener and route request 
    httpListener
        .open()
        .then([&httpListener,listenerName](){ 
            Logger logger;
            std::string logMessage(listenerName + "started");

            logger.log(logMessage);

        }).wait();

    // JUST WAIT - we do not want the application to stop
    while (true);

}

Now I do not know how many threads there are - it is basically just the number of records read from a database table.

for each (Listener l in ls.Select(m.GetId()))
{
    l.Start();
}

Only the first thread is started and runs, Which is kind of logical in that the only thing stopping the thread from running is a permanent loop.

If however it is run this way;

    std::vector<thread> listener_threads;

    for each (Listener l in ls.Select(m.GetId()))
    {
        listener_threads.push_back(thread{ &Listener::Start, &l });
    }

None of the threads seem to be running - none of the listeners reply to any request.

So the question is how can you run an indeterminate number of threads in a C++ application.

Paul S Chapman
  • 832
  • 10
  • 37

1 Answers1

0

The way to do this is first collect all the listener instances in a vector. Then loop through this vector creating another vector with the actual threads.

// collect all the listeners into a vector

for (auto& m : rm.Select()) {
    for (auto& l : ls.Select(m.GetId())) {
        lvector.push_back(l);
    }
}

// now create threads for each listener
for (auto& lstnr : lvector)
{
    listener_threads.push_back(std::thread{ &Listener::Start, &lstnr });
}

// now join with this thread.
for (auto& t : listener_threads)
{
    t.join();
}

As I have a while(true) at the bottom of each thread - then the application just continues to run while listening on all the required domains.

I think there maybe an issue with scope as the lvector needs to be outside the for loops and they are all added.

Paul S Chapman
  • 832
  • 10
  • 37