diff --git a/src/main.c b/src/main.c index 4088372..e887e8a 100644 --- a/src/main.c +++ b/src/main.c @@ -1,3 +1,12 @@ +/* + * Design Doc: + * The server is broken into the following files: + * - main.c: Argument parsing and high-level control + * - http.c: HTTP request parsing and response formatting + * - server.c: Abstraction over sockets + * - threadpool.c: Thread pool and wokr queue implementation + * - util.c: Misc. utility functions + */ #include "http.h" #include "server.h" #include "threadpool.h" @@ -327,6 +336,10 @@ static void handle_connection(void *arg) { fclose(conn); } +static void fclose_free_func(void *file) { + fclose(file); +} + int main(int argc, const char **argv) { setenv("POSIXLY_CORRECT", "1", true); GlobalFlags flags = DEFAULT_FLAGS; @@ -367,7 +380,7 @@ int main(int argc, const char **argv) { close(conn_fd); continue; } - thread_pool_enqueue(pool, handle_connection, conn); + thread_pool_enqueue(pool, handle_connection, conn, fclose_free_func); } destroy_thread_pool(pool); destroy_server(server); diff --git a/src/threadpool.c b/src/threadpool.c index 1333001..a7a8dc1 100644 --- a/src/threadpool.c +++ b/src/threadpool.c @@ -8,6 +8,7 @@ struct thread_pool_queue { Task task; void *arg; + FreeFunc ff; struct thread_pool_queue *next; }; @@ -91,15 +92,25 @@ void destroy_thread_pool(ThreadPool *pool) { free(pool->threads); pthread_mutex_destroy(&pool->queue_mtx); pthread_cond_destroy(&pool->queue_cnd); + struct thread_pool_queue *queue = pool->queue; + while (queue) { + struct thread_pool_queue *next = queue->next; + if (queue->ff) { + queue->ff(queue->arg); + } + free(queue); + queue = next; + } free(pool); } -void thread_pool_enqueue(ThreadPool *pool, Task task, void *arg) { +void thread_pool_enqueue(ThreadPool *pool, Task task, void *arg, FreeFunc ff) { pthread_mutex_lock(&pool->queue_mtx); struct thread_pool_queue *new = malloc_safe(sizeof(struct thread_pool_queue)); new->task = task; new->arg = arg; + new->ff = ff; new->next = pool->queue; pool->queue = new; pthread_cond_signal(&pool->queue_cnd); diff --git a/src/threadpool.h b/src/threadpool.h index 4007d56..0d45542 100644 --- a/src/threadpool.h +++ b/src/threadpool.h @@ -6,11 +6,12 @@ typedef struct _ThreadPool ThreadPool; typedef void (*Task)(void *); +typedef void (*FreeFunc)(void *); ThreadPool *make_thread_pool(size_t parallelism, sigset_t sig_mask); void destroy_thread_pool(ThreadPool *pool); -void thread_pool_enqueue(ThreadPool *pool, Task task, void *arg); +void thread_pool_enqueue(ThreadPool *pool, Task task, void *arg, FreeFunc ff); #endif