Use allocator per session thread
This commit is contained in:
parent
e7e140f341
commit
c66d8726ed
2 changed files with 16 additions and 14 deletions
|
@ -3,8 +3,5 @@ const network = @import("network.zig");
|
|||
const handlers = @import("handlers.zig");
|
||||
|
||||
pub fn main() !void {
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
const allocator = gpa.allocator();
|
||||
|
||||
try network.listen(allocator);
|
||||
try network.listen();
|
||||
}
|
||||
|
|
|
@ -2,7 +2,7 @@ const std = @import("std");
|
|||
const Session = @import("Session.zig");
|
||||
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;
|
||||
var listener = try addr.listen(.{
|
||||
.kernel_backlog = 100,
|
||||
|
@ -15,22 +15,27 @@ pub fn listen(allocator: Allocator) !void {
|
|||
const conn = listener.accept() catch continue;
|
||||
errdefer conn.stream.close();
|
||||
|
||||
const session = try allocator.create(Session);
|
||||
session.* = Session.init(conn.address, conn.stream, allocator);
|
||||
|
||||
const thread = try std.Thread.spawn(.{}, runSession, .{session});
|
||||
const thread = try std.Thread.spawn(.{}, runSession, .{ conn.address, conn.stream });
|
||||
thread.detach();
|
||||
}
|
||||
}
|
||||
|
||||
fn runSession(s: *Session) void {
|
||||
std.log.info("new connection from {}", .{s.address});
|
||||
fn runSession(address: std.net.Address, stream: std.net.Stream) !void {
|
||||
std.log.info("new connection from {}", .{address});
|
||||
|
||||
if (s.run()) |_| {
|
||||
std.log.info("client from {} disconnected", .{s.address});
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
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| {
|
||||
std.log.err("session disconnected with an error: {}", .{err});
|
||||
}
|
||||
|
||||
s.allocator.destroy(s);
|
||||
allocator.destroy(session);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue