sample_web_server: fix CTRL-C and high cpu usage issue

fix #4
This commit is contained in:
Tao Guo
2024-11-14 14:21:35 -08:00
parent 435674a6f6
commit 5adc39806a

View File

@ -76,7 +76,7 @@ pub fn main() !void {
io.accept(*Acceptor, &acceptor, acceptCallback, &acceptor_completion, listener);
// Wait while accepting.
while (acceptor.accepting) try io.tick();
while (acceptor.accepting and running.load(.monotonic)) try io.run_for_ns(1 * std.time.ns_per_ms);
// Reset accepting flag.
acceptor.accepting = true;
@ -111,7 +111,8 @@ fn logError(queue_mutex: *Thread.Mutex, queue: *Queue) void {
const Client = struct {
allocator: mem.Allocator,
completion: IO.Completion,
send_completion: IO.Completion,
recv_completion: IO.Completion,
io: *IO,
recv_buf: [Config.recv_buf_len]u8,
socket: posix.socket_t,
@ -143,7 +144,8 @@ fn handleClient(queue_mutex: *Thread.Mutex, queue: *Queue) !void {
var client_ptr = try allocator.create(Client);
client_ptr.allocator = allocator;
client_ptr.io = &io;
client_ptr.completion = undefined;
client_ptr.send_completion = undefined;
client_ptr.recv_completion = undefined;
client_ptr.recv_buf = undefined;
client_ptr.socket = socket;
client_ptr.thread_id = thread_id;
@ -153,13 +155,13 @@ fn handleClient(queue_mutex: *Thread.Mutex, queue: *Queue) !void {
*Client,
client_ptr,
recvCallback,
&client_ptr.completion,
&client_ptr.recv_completion,
socket,
&client_ptr.recv_buf,
);
}
try io.tick();
try io.run_for_ns(1 * std.time.ns_per_ms);
}
}
@ -187,6 +189,16 @@ fn recvCallback(
return;
}
// Try to receive from client again (keep-alive).
client_ptr.io.recv(
*Client,
client_ptr,
recvCallback,
completion,
client_ptr.socket,
&client_ptr.recv_buf,
);
const response =
\\HTTP/1.1 200 OK
\\Connection: Keep-Alive
@ -203,7 +215,7 @@ fn recvCallback(
*Client,
client_ptr,
sendCallback,
completion,
&client_ptr.send_completion,
client_ptr.socket,
response,
);
@ -214,18 +226,9 @@ fn sendCallback(
completion: *IO.Completion,
result: IO.SendError!usize,
) void {
_ = completion; // autofix
const sent = result catch @panic("sendCallback");
log.debug("{}: Sent {} to {}", .{ client_ptr.thread_id, sent, client_ptr.socket });
// Try to receive from client again (keep-alive).
client_ptr.io.recv(
*Client,
client_ptr,
recvCallback,
completion,
client_ptr.socket,
&client_ptr.recv_buf,
);
}
fn closeCallback(