Fix mem leak

This commit is contained in:
2026-05-25 17:37:16 -07:00
parent 1005650ea6
commit ba8c94d971
3 changed files with 28 additions and 3 deletions
+14 -1
View File
@@ -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);
+12 -1
View File
@@ -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);
+2 -1
View File
@@ -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