I have a client/server program which I would like to read in a client's request and then create a thread for each request that goes through and processes each accordingly. But my issue is that when I run a request and have it sleep for 5 seconds and then have another request come in after this with no sleep time. Should it not be blocked until the '5 second' thread is finished executing before it can execute this code? Here is the rest of the main in case you would like to see that also.
Code:
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include "http.h"
#include "myTCP.h"
void *runner( void * ptr);
struct parm{
int socket;
char path[100];
char *from;
char *userAgent;
};
int thread_count=0; //Current amount of threads operating
int read_count=0;
int write_count=0;
pthread_mutex_t mutex;
pthread_mutexattr_t attr;
int main(int argc, char *argv[]) {
int port=-999; /* port number to connect to, on server */
int msock=-999; /* socket descriptor for connection */
int iRet; //Return value for pthread_create
int pid; //process id
int MAX_THREAD=-999; //Maximum amount of threads allowed to run
char *server_full_message = "HTTP/1.0 502 Server temporarily overloaded\n\n502 SERVER TEMPORARILY OVERLOADED\n";
struct parm *p;
// p=(parm *)malloc(sizeof(parm)*n); //Use this when you have a thread pool
p=(struct parm *)malloc(sizeof(struct parm)); //Allocate space for the p structure
pid = getpid();
if(argc==1) {
p->userAgent = argv[0];
port = WL_PORT;
MAX_THREAD = 5;
} else if(argc==2) {
p->userAgent = argv[0];
MAX_THREAD = atoi(argv[1]);
port = WL_PORT;
} else if (argc==3) {
p->userAgent = argv[0];
MAX_THREAD = atoi(argv[1]);
if(atoi(argv[2]) >1024) port = atoi(argv[2]);
else port = WL_PORT;
} else {
fprintf(stderr,"ERROR: useage: <%s> <path> [<Max # Threads>] [<Port>]\n", argv[0]);
exit(1);
}
#ifdef DEBUG
fprintf(stderr,"DEBUG: %d %s will listen on port %d\n", pid, argv[0], port);
fprintf(stderr,"DEBUG: MAX_THREAD = %d\n", MAX_THREAD);
#endif
pthread_t aThread; //Thread to be executed
msock = myTCPserverSocket(port, argv[0]);
// Now accept connections and service clients forever,
while(1) {
/*Accept the client's socket*/
p->socket = myTCPaccept(msock, argv[0]);
if(thread_count <= MAX_THREAD) {
pthread_mutex_init(&mutex, &attr);
iRet = pthread_create(&aThread, NULL, runner, (void *) p);
thread_count++;
// pthread_join(aThread, NULL);
}
else { //The server is currently operating with the maximum number of threads
fprintf(stdout, "Successfully Received Messsage From Client\n");
//Respond to the Client notifying them that the server was too busy
write(p->socket, server_full_message, strlen(server_full_message));
fprintf(stdout, "Successfully Responded To Client\n");
myTCPclose(p->socket);
}
}
}