Make HttpServer utilize Queue.

This commit is contained in:
Jordan Bancino 2022-08-24 10:06:14 -04:00
parent ab4afe1587
commit be001fb17a
3 changed files with 76 additions and 9 deletions

View file

@ -24,8 +24,10 @@
#include <NonPosix.h>
#include <HttpServer.h>
#include <Queue.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
@ -47,8 +49,52 @@ struct HttpServer
HttpHandler *requestHandler;
void *handlerArgs;
Queue *connQueue;
pthread_mutex_t connQueueMutex;
};
static int
QueueConnection(HttpServer * server, int fd)
{
FILE *fp;
int result;
if (!server)
{
return 0;
}
fp = fdopen(fd, "rw");
if (!fp)
{
return 0;
}
pthread_mutex_lock(&server->connQueueMutex);
result = QueuePush(server->connQueue, fp);
pthread_mutex_unlock(&server->connQueueMutex);
return result;
}
static FILE *
DequeueConnection(HttpServer * server)
{
FILE *fp;
if (!server)
{
return NULL;
}
pthread_mutex_lock(&server->connQueueMutex);
fp = QueuePop(server->connQueue);
pthread_mutex_unlock(&server->connQueueMutex);
return fp;
}
HttpServer *
HttpServerCreate(unsigned short port, unsigned int nThreads, unsigned int maxConnections,
HttpHandler * requestHandler, void *handlerArgs)
@ -67,6 +113,13 @@ HttpServerCreate(unsigned short port, unsigned int nThreads, unsigned int maxCon
return NULL;
}
server->connQueue = QueueCreate(maxConnections);
if (!server->connQueue)
{
free(server);
return NULL;
}
server->sd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
if (server->sd < 0)
@ -120,6 +173,7 @@ HttpServerEventThread(void *args)
{
HttpServer *server = (HttpServer *) args;
struct pollfd pollFds[1];
FILE *fp;
server->isRunning = 1;
server->stop = 0;
@ -147,7 +201,14 @@ HttpServerEventThread(void *args)
continue;
}
close(connFd);
QueueConnection(server, connFd);
}
/* Wait on all threads in the thread pool */
while ((fp = DequeueConnection(server)))
{
fclose(fp);
}
server->isRunning = 0;

View file

@ -23,12 +23,14 @@
*/
#include <Queue.h>
#include <stdlib.h>
struct Queue
{
void **items;
size_t size;
int front;
int rear;
size_t front;
size_t rear;
};
Queue *
@ -56,8 +58,10 @@ QueueCreate(size_t size)
}
q->size = size;
q->front = -1;
q->rear = -1;
q->front = size + 1;
q->rear = size + 1;
return q;
}
void
@ -72,7 +76,7 @@ QueueFree(Queue * q)
}
int
QueueFull(Queue *)
QueueFull(Queue * q)
{
if (!q)
{
@ -83,14 +87,14 @@ QueueFull(Queue *)
}
int
QueueEmpty(Queue *)
QueueEmpty(Queue * q)
{
if (!q)
{
return 0;
}
return q->front == -1;
return q->front == q->size + 1;
}
int
@ -106,7 +110,7 @@ QueuePush(Queue * q, void *element)
return 0;
}
if (q->front == -1)
if (q->front == q->size + 1)
{
q->front = 0;
}

View file

@ -24,6 +24,8 @@
#ifndef TELODENDRIA_QUEUE_H
#define TELODENDRIA_QUEUE_H
#include <stddef.h>
typedef struct Queue Queue;
extern Queue *