Std :: thread constructor sometimes doesn't return (vc ++ 2014 preview)

I have a problem in my C ++ HTTP server where sometimes a new thread is created to handle a client request that is not returned. I've tried everything I can think of (limit the number of concurrent threads) and other than limiting the number of threads to 1, it doesn't fix.

This happens in my other program as well, using the VC ++ 2014 Preview compiler as well.

This is the sample code where the problem occurs. I have verified that it sometimes prints "About creating a new stream ..." but does not print the next "Detach new stream ..." or "End reception ..."

Sometimes, after a couple of minutes, or when I apply some kind of external influence (for example, pausing the application in the debugger, which shows that the code will be displayed currently in the thread constructor), the program will eventually start working correctly again.I have also confirmed. that other threads always continue to run correctly at all times.

Threadcount never makes it past 6 or 7, even when I refresh my local webpage with ~ 20 images on it as fast as possible, so I don't think the problem has anything to do with too many threads at once ...

The only thing I can think of is "threadCount" because I am decrementing it at the end of the thread function, but the thread is still technically there at the time it is decremented. But I don't think this is a problem because sometimes the thread building hangs even after refreshing the page twice, and my test computer has 8 hardware threads.

Blocking when threadCount is greater than 1 or 2 seems to be reliable, but it probably isn't. Limiting to 4 is not reliable.

atomic_int threadCount = 0;
bool Server::checkForNewConnection()
{
    sockaddr clientAddress;
    socklen_t clientAddressLength = sizeof(clientAddress);
    fd_set readSet;
    FD_ZERO(&readSet);
    FD_SET(this->serverSocket, &readSet);

    const auto clientSocket = accept(this->serverSocket, &clientAddress, &clientAddressLength);

    cout << "Incremented threadcount: " << ++threadCount << endl;

    if (clientSocket < 0 || clientSocket == INVALID_SOCKET)
    {
        closesocket2(clientSocket);
        return false;
    }

    sockaddr_in* add2;
    add2 = reinterpret_cast<sockaddr_in*>(&clientAddress);

    const string clientAddressString(inet_ntoa(add2->sin_addr));

    cout << "About to create new thread..." << endl;
    thread serverThread(&ForkThread, this, clientSocket, clientAddressString, false);
    cout << "Detaching new thread..." << endl;
    serverThread.detach();
    cout << "Ending accept..." << endl;

    return true;

      

}

+3


source to share





All Articles