commit 2b4f3de
uint
·
2026-03-15 17:21:46 +0000 UTC
parent 02c88e3
replace semaphore.h with slot tracking
1 files changed,
+37,
-7
+37,
-7
1@@ -10,7 +10,6 @@
2
3 #include <errno.h>
4 #include <fcntl.h>
5-#include <semaphore.h>
6 #include <signal.h>
7 #include <stdarg.h>
8 #include <stdbool.h>
9@@ -43,15 +42,18 @@ static void apply_rlimits(void);
10 static int client_thread(void* arg);
11 static void fd_set_cloexec(int fd);
12 static void sock_set_timeouts(int fd);
13+static void release_slot(void);
14+static int try_acquire_slot(void);
15
16 void die(const char* s, int e);
17 void run(void);
18 void setup(void);
19
20-static sem_t slots;
21 static int sock;
22 struct library lib;
23 mtx_t lib_lock;
24+static mtx_t slots_lock;
25+static int slots_available;
26
27 static void apply_rlimits(void)
28 {
29@@ -75,7 +77,7 @@ static int client_thread(void* arg)
30 shutdown(c, SHUT_WR);
31 close(c);
32
33- (void)sem_post(&slots);
34+ release_slot();
35 return 0;
36 }
37
38@@ -96,6 +98,33 @@ static void sock_set_timeouts(int fd)
39 (void)setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
40 }
41
42+static void release_slot(void)
43+{
44+ if (mtx_lock(&slots_lock) != thrd_success)
45+ return;
46+
47+ if (slots_available < max_clients)
48+ slots_available++;
49+
50+ (void)mtx_unlock(&slots_lock);
51+}
52+
53+static int try_acquire_slot(void)
54+{
55+ int ok = 0;
56+
57+ if (mtx_lock(&slots_lock) != thrd_success)
58+ return -1;
59+
60+ if (slots_available > 0) {
61+ slots_available--;
62+ ok = 1;
63+ }
64+
65+ (void)mtx_unlock(&slots_lock);
66+ return ok;
67+}
68+
69 void die(const char* s, int e)
70 {
71 perror(s);
72@@ -117,7 +146,7 @@ void run(void)
73 fd_set_cloexec(c);
74
75 /* client cap. if full 503 and close */
76- if (sem_trywait(&slots) < 0) {
77+ if (try_acquire_slot() != 1) {
78 /* short 503 + retry after */
79 static const char resp[] =
80 "HTTP/1.1 503 Service Unavailable\r\n"
81@@ -140,7 +169,7 @@ void run(void)
82 if (err != thrd_success) {
83 LOG(true, "CORE", "thrd_create FAILED %d", err);
84 close(c);
85- (void)sem_post(&slots);
86+ release_slot();
87 continue;
88 }
89
90@@ -158,8 +187,9 @@ void setup(void)
91 if (mtx_init(&lib_lock, mtx_plain) != thrd_success)
92 die("mtx_init", EXIT_FAILURE);
93
94- if (sem_init(&slots, 0, max_clients) < 0)
95- die("sem_init", EXIT_FAILURE);
96+ if (mtx_init(&slots_lock, mtx_plain) != thrd_success)
97+ die("mtx_init", EXIT_FAILURE);
98+ slots_available = max_clients;
99
100 int ret = 1;
101 sock = socket(AF_INET, SOCK_STREAM, 0);