Беннито
Беннито

Reputation: 27

Will the thread die after his caller will finish the job?

One of my class functions running in infinity loop and accepting clients with the function Server::accept(). So my question is: will userThread die after accept() will finish his job, or it will run forever because of the infinity loop in second function that calls accept() forever?

void Server::accept()
{
    // notice that we step out to the global namespace
    // for the resolution of the function accept

    // this accepts the client and create a specific socket from server to this client
    SOCKET client_socket = ::accept(_serverSocket, NULL, NULL);

    if (client_socket == INVALID_SOCKET)
        throw std::exception(__FUNCTION__);

    std::cout << "Client accepted. Server and client can speak" << std::endl;

    // the function that handle the conversation with the client
    std::thread userThread(&clientHandler, client_socket);
    userThread.detach();
}

Upvotes: 0

Views: 79

Answers (2)

N. Prone
N. Prone

Reputation: 180

each thread:

  1. spawns a new thread.
  2. detaches the new thread.

Since #1 happens before #2, you will always end up with a new live thread before the original thread dies.

Upvotes: 0

Chnossos
Chnossos

Reputation: 10476

userThread has been detached so the system thread will run until clientHandler() finishes or throws. Server::accept() will return immediately.

Upvotes: 3

Related Questions