Don't use multi threading where it is not required

This commit is contained in:
2025-04-06 10:53:55 -04:00
parent 6b38d5bb74
commit 8278648ba9

View File

@@ -79,13 +79,15 @@ pub fn sendInitialConnection(payload: []const u8, initial_port: u16, allocator:
return msg;
}
var setting_up_socket: std.Thread.Semaphore = std.Thread.Semaphore{};
pub fn connect(payload: []const u8, allocator: Allocator) !?SaprusMessage {
var initial_port: u16 = 0;
if (rand) |r| {
initial_port = r.intRangeAtMost(u16, 1024, 65000);
} else unreachable;
var initial_conn_res: ?SaprusMessage = null;
errdefer if (initial_conn_res) |c| c.deinit(allocator);
fn awaitSentinelConnectionResponse(
res: *?SaprusMessage,
err: *?anyerror,
allocator: Allocator,
) !void {
var sock = try network.Socket.create(.ipv4, .udp);
defer sock.close();
@@ -99,47 +101,13 @@ fn awaitSentinelConnectionResponse(
try sock.setReadTimeout(1_000_000);
try sock.bind(bind_addr);
// Signal that the socket is ready to receive data.
setting_up_socket.post();
var response_buf: [4096]u8 = undefined;
_ = try sock.receive(&response_buf);
const len = sock.receive(&response_buf) catch |e| {
err.* = e;
return;
};
res.* = try SaprusMessage.fromBytes(response_buf[0..len], allocator);
}
pub fn connect(payload: []const u8, allocator: Allocator) !?SaprusMessage {
var initial_port: u16 = 0;
if (rand) |r| {
initial_port = r.intRangeAtMost(u16, 1024, 65000);
} else unreachable;
var err: ?anyerror = null;
var initial_conn_res: ?SaprusMessage = null;
errdefer if (initial_conn_res) |c| c.deinit(allocator);
const response_thread = try std.Thread.spawn(
.{},
awaitSentinelConnectionResponse,
.{
&initial_conn_res,
&err,
allocator,
},
);
// Block until the socket is set up.
try setting_up_socket.timedWait(5 * 1000 * 1000 * 1000 * 1000);
const msg = try sendInitialConnection(payload, initial_port, allocator);
// Await response from the sentinel
response_thread.join();
var response_buf: [4096]u8 = undefined;
_ = try sock.receive(&response_buf);
const len = try sock.receive(&response_buf);
initial_conn_res = try SaprusMessage.fromBytes(response_buf[0..len], allocator);
// Complete handshake after awaiting response
try broadcastSaprusMessage(msg, randomPort(), allocator);