0

I started writing a c web server a while ago (windows 8), but I tried using only threads by myself, without using the select() option.

This is my main loop, and I'm opening each new thread like this:

uintptr_t new_thread;
while (client_sock = accept(server->sock, (struct sockaddr *)&client_info, &size))
{
    if (client_sock <= 0) quit();
    printf("\n[***] : Got a connection from localhost on port %d\n",ntohs(client_info.sin_port));

    code = init_connection(client_sock);
    if (code)
    {
        new_thread = _beginthread(handle_connection, 0, ID++, client_sock);
        if (new_thread == -1)
        {
            fprintf(stderr, "Could not create thread for sending data: %d\n", GetLastError());
            closesocket(client_sock);
            quit();
        }
    }
    else
    {
        debug("Failed to init connection");
        closesocket(client_sock);
        debug("Connection to client ended");
    }   
}

First of all, I would love to here if I can make this code better.

Testing this program by trying to enter the localhost from chrome, I see that no more data is sent (after recieving one http request).

My question is what would be the best way for the program to act then: close the thread and when another request will be made it will open a new one? if so, how do I close that thread? if not, when should I close that thread?

Ofer Arial
  • 1,129
  • 1
  • 10
  • 25
  • For this case it might be easier to fork() instead of creating threads. Ok, you might not have this option on windows... – Ctx Mar 08 '17 at 13:37
  • Yes, sorry for that. Also, not interested of using CygWin at the moment – Ofer Arial Mar 08 '17 at 13:40

1 Answers1

0

Normally, when implementing a server that forks separate processes, I would make the child process stay alive to serve predefined amount of requests (e.g. 100) and then kill itself. This is to reduce overhead created by forking and on the other hand recover from possible memory leaks or other problems in the process. Threads are lighter than processes, so it may make sense to close them faster.

I think you should compare the benefits and drawbacks. Measure the overhead of thread creation and closing compared to keeping them alive. In any case you must make sure that there is limit on the number threads you have alive at one time.

About the windows specifics on creating ans closing the thread you could go and add e.g. this response.

Community
  • 1
  • 1
diidu
  • 2,823
  • 17
  • 32