QUOTE: Be your own kind of beautiful.

fix: Fixed high CPU usage bug - libhttp - A basic HTTP Framework

libhttp

A basic HTTP Framework
git clone git://192.168.2.2/libhttp
Log | Files | Refs | README

commit 82a811c9136c0bd5ec78030784d1db3cbe28328f
parent 00aab001e40379f130096573da5c723ef5ff5bd7
Author: typable <contact@typable.dev>
Date:   Wed,  8 May 2024 11:53:01 +0200

fix: Fixed high CPU usage bug

Diffstat:
Mlibhttp.c | 20+++++++++++++++-----
1 file changed, 15 insertions(+), 5 deletions(-)

diff --git a/libhttp.c b/libhttp.c @@ -2,6 +2,7 @@ #include <stdlib.h> #include <stdbool.h> #include <string.h> +#include <time.h> #include <unistd.h> #include <pthread.h> #include <netdb.h> @@ -298,11 +299,14 @@ http_request_t http_read_request(conn_t *conn) { int len = 0; int ln = 0; int start = 0; - char buffer[10240]; + char buffer[MAX_REQUEST_HEAD_SIZE]; http_request_t request = { conn, NULL, NULL, NULL, NULL, 0, NULL, 0 }; while (true) { char c; - http_read(conn, &c, 1); + int read = http_read(conn, &c, 1); + if (read == 0) { + break; + } // break if too long if (len == MAX_REQUEST_HEAD_SIZE) { perror("request is too long"); @@ -469,7 +473,10 @@ void *http_handle_server(void *ptr) { fds[0].fd = sockfd; fds[0].events = POLLIN | POLLPRI; while (!http_quit) { - usleep(100000); + struct timespec sleep_req, sleep_rem; + sleep_req.tv_sec = 0; + sleep_req.tv_nsec = 100000000; + nanosleep(&sleep_req, &sleep_rem); if (poll(fds, 1, 100)) { conn_t *conn = malloc(sizeof(conn_t)); conn->addr_len = sizeof(conn->addr); @@ -480,8 +487,11 @@ void *http_handle_server(void *ptr) { } else { pthread_t thread; - pthread_create(&thread, 0, http_handle_client, (void *) conn); - pthread_detach(thread); + pthread_attr_t thread_attr; + pthread_attr_init(&thread_attr); + pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED); + pthread_create(&thread, &thread_attr, http_handle_client, (void *) conn); + pthread_attr_destroy(&thread_attr); } } }