I'm trying to create a simple server that starts a new thread for each new client that connects. I know I can use fork(), but I've heard that threads are more efficient. Also I have some global queues, so if I used fork(), each process would get their own version of the queues. (I could fix this with shared memory).

But I'm not sure where to implement this in my code.
Heres the pseudocode of my server and main accept() loop:

Global queue1;
Global queue2;

<create socket and request socket, fill address structure, bind(), listen()>
while(1) {
    <socket = accept()>
    <close request socket>
    <Processing the request>
    <Closing socket>
}

So I need to know where/how, in my code, to implement threads, and which type of threads to use. It is supposed to run on Linux.
Also I need to know how to synchronize Global queue1 and Global queue2 so that the threads can access and write/delete from them without problems.

Trying to recall stuff:

I'm not sure why you're closing the listening request socket, server should always have that on... anyway how about:

<create listening sock, etc.>
while(1)
{
    <accept request > //accept() creates a new socket leaving listening socket alone to continue listening
    <create new thread in socket> //calling pthread_function, provide socket and processing function as arguments
}

void functiontoprocessrequest()
{
    <Processing the request>
    <Closing socket created during accept()>
}

for the create thread function use pthread.h (POSIX thread) for linux:
pthread_create(&childthread, 0, &functiontoprocessrequest, &newsocketdescriptor);

or something similar

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.