0

I had simple web server that fork() and use accept() inside child process.

Here is pseudo-code:

void server_child_process(int server_socket){
    // ...

    while (true){
        if ( ( client = accept(server_socket, addr, addrlen) ) == false ){
            server_debug("Can not socket_accept()...");
        }
        //...
    }
}

accept() seems to have no problem and no need for any synchronization.

With fork() model you can have several accept() at the same time. Single connection is always accepted once from single random child process.
(e.g. no connection is accepted from two children)

This model is often called pre-fork, because theoretically after initial fork() no new fork() are made.

Can I do the same in a thread?

Nick
  • 9,962
  • 4
  • 42
  • 80

1 Answers1

0

As long as you only have one thread operating on server_socket at a time, you can safely call accept on that socket in a thread.

You'll most likely want one thread that calls accept to get new connections, and multiple worker threads that can each handle a connection. The best way to handle this it to create a number of worker threads at startup and have a queue of connections for each one, each with an associated mutex.

The accepting thread will choose one of the workers to handle a new connection. It then locks the mutex for that worker's queue, places the connection on the queue, and unlocks. Each worker can then lock the mutex for its queue, retrieve a connection from the queue, unlock, then process the connection.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • "As long as you only have one thread operating on server_socket at a time, you can safely call accept on that socket in a thread" - well this is my point. with fork() you can have several accept()'s in parallel from different children. Single connection is always accepted from single child. And no two children accept same connection. I will edit now. – Nick Jan 10 '17 at 15:46