Ithilion
Ithilion

Reputation: 140

Wait for all child thread to finish (in C)

Code first

while(running)
{
    memset(&tcp_client, 0, tcp_client_len);

    FD_ZERO(&readFDs);
    FD_SET(tcp_server_s, &readFDs);
    tv.tv_sec = 1;
    if(select(0, &readFDs, NULL, NULL, &tv))
    {
        if( (tcp_client_s = accept(tcp_server_s, (struct sockaddr *)&tcp_client,&tcp_client_len)) == INVALID_SOCKET )
        {
            cli_log(PROTO_TCP, LOG_ERROR, "(%d) accept() failed\n", WSAGetLastError());
            continue;
        }
        cli_log(PROTO_TCP, LOG_COMM, "(%s:%d) accepted connection\n", inet_ntoa(tcp_client.sin_addr), ntohs(tcp_client.sin_port));

        CreateThread(NULL, 0, tcp_thread, (LPVOID)tcp_client_s, 0, NULL);
    }
}

This is part of my TCP threads handler. What i would like to know is how to make it wait for all his child thread to finish before exiting when not running anymore (CTRL+C signal).

Upvotes: 0

Views: 337

Answers (1)

hmjd
hmjd

Reputation: 121971

  1. Maintain a list of HANDLEs containing the handles of the successfully created threads (a HANDLE is the result of CreateThread() if successful).
  2. Use WaitForMultipleObjects() to join on each of the threads prior to application exit.

Upvotes: 3

Related Questions