Use allocator per session thread

This commit is contained in:
xeon 2024-06-26 18:26:24 +03:00
parent e7e140f341
commit c66d8726ed
2 changed files with 16 additions and 14 deletions

View file

@ -3,8 +3,5 @@ const network = @import("network.zig");
const handlers = @import("handlers.zig"); const handlers = @import("handlers.zig");
pub fn main() !void { pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; try network.listen();
const allocator = gpa.allocator();
try network.listen(allocator);
} }

View file

@ -2,7 +2,7 @@ const std = @import("std");
const Session = @import("Session.zig"); const Session = @import("Session.zig");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
pub fn listen(allocator: Allocator) !void { pub fn listen() !void {
const addr = std.net.Address.parseIp4("0.0.0.0", 23301) catch unreachable; const addr = std.net.Address.parseIp4("0.0.0.0", 23301) catch unreachable;
var listener = try addr.listen(.{ var listener = try addr.listen(.{
.kernel_backlog = 100, .kernel_backlog = 100,
@ -15,22 +15,27 @@ pub fn listen(allocator: Allocator) !void {
const conn = listener.accept() catch continue; const conn = listener.accept() catch continue;
errdefer conn.stream.close(); errdefer conn.stream.close();
const session = try allocator.create(Session); const thread = try std.Thread.spawn(.{}, runSession, .{ conn.address, conn.stream });
session.* = Session.init(conn.address, conn.stream, allocator);
const thread = try std.Thread.spawn(.{}, runSession, .{session});
thread.detach(); thread.detach();
} }
} }
fn runSession(s: *Session) void { fn runSession(address: std.net.Address, stream: std.net.Stream) !void {
std.log.info("new connection from {}", .{s.address}); std.log.info("new connection from {}", .{address});
if (s.run()) |_| { var gpa = std.heap.GeneralPurposeAllocator(.{}){};
std.log.info("client from {} disconnected", .{s.address}); defer if (gpa.deinit() == .leak) std.log.err("memory leaks were detected for session at {}", .{address});
const allocator = gpa.allocator();
const session = try allocator.create(Session);
session.* = Session.init(address, stream, allocator);
if (session.*.run()) |_| {
std.log.info("client from {} disconnected", .{address});
} else |err| { } else |err| {
std.log.err("session disconnected with an error: {}", .{err}); std.log.err("session disconnected with an error: {}", .{err});
} }
s.allocator.destroy(s); allocator.destroy(session);
} }