Search code examples
c++multithreadingblock

Thread is blocking whole program


I'm trying to make a multiclient server. I have this thread:

void client_thread(int new_socket)
{
    int size;
    char inbuffer[BUF];

    do
    {
        cout << "Waiting for messages: " << endl;
        size = recv(new_socket, inbuffer, BUF, 0);
    } while (true);
}

and this main procedure:

int main()
{
    while (true)
    {
        //waiting for clients
        cout << "Waiting for connections..." << endl;
        new_socket = accept ( create_socket, (struct sockaddr *) &cliaddress, &addrlen );

        //new client connected
        if (new_socket > 0)
        {
            //start thread
            thread(client_thread, new_socket).join();
        }
    }
    return 0;
}

When the first client connects, the thread starts and the server is waiting for messages from him. But the server doesn't wait for new clients anymore. I don't know why. Is it because of the infinite do-while loop inside the thread-function? What's the point of threads if they block your whole program if they contain infinite loops?


Solution

  • The main routine blocks, because it waits for the thread to finish: join().

    If you don't want to block, then don't join() your client_thread.

    This exception might come from the destruction of your anonymous thread object. When you leave the scope of if() all objects in this scope are destroyed. From http://en.cppreference.com/w/cpp/thread/thread/~thread you can see, the destructor calls terminate(). To avoid it, you can call detach(). So instead of thread(client_thread, new_socket).join();, you must say thread(client_thread, new_socket).detach();.