summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorRobby Zambito <contact@robbyzambito.me>2025-04-06 10:53:55 -0400
committerRobby Zambito <contact@robbyzambito.me>2025-04-06 13:08:09 -0400
commit8278648ba99c3adedc2e09230b224508de5fd4b5 (patch)
treea0e65a521323833bec056cefd29fabd8071abc3b /src
parent6b38d5bb7440ba6bc288a09a393e8925b8085ee9 (diff)
Don't use multi threading where it is not required
Diffstat (limited to 'src')
-rw-r--r--src/saprus.zig54
1 files changed, 11 insertions, 43 deletions
diff --git a/src/saprus.zig b/src/saprus.zig
index b8a5ea4..e89998a 100644
--- a/src/saprus.zig
+++ b/src/saprus.zig
@@ -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();
+ const msg = try sendInitialConnection(payload, initial_port, allocator);
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);
+ const len = try sock.receive(&response_buf);
- // Await response from the sentinel
- response_thread.join();
+ initial_conn_res = try SaprusMessage.fromBytes(response_buf[0..len], allocator);
// Complete handshake after awaiting response
try broadcastSaprusMessage(msg, randomPort(), allocator);