Created
June 18, 2024 18:51
-
-
Save geon/5e2dff0a76926ec79695ee722caa21f4 to your computer and use it in GitHub Desktop.
Experiment with sending messages between theads.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
fn Signal(comptime T: type) type { | |
return struct { | |
message: T, | |
readyToRecieveMessage: std.Thread.Semaphore, | |
messageHasBeenSet: std.Thread.Semaphore, | |
const Self = @This(); | |
fn init() Self { | |
return Self{ | |
.message = "undefined", | |
.readyToRecieveMessage = std.Thread.Semaphore{}, | |
.messageHasBeenSet = std.Thread.Semaphore{}, | |
}; | |
} | |
fn send(this: *Self, message: T) void { | |
this.readyToRecieveMessage.wait(); | |
this.message = message; | |
this.messageHasBeenSet.post(); | |
} | |
fn recieve(this: *Self) T { | |
this.readyToRecieveMessage.post(); | |
this.messageHasBeenSet.wait(); | |
return this.message; | |
} | |
}; | |
} | |
fn send2(signal: *Signal([]const u8), a: []const u8, b: []const u8) void { | |
signal.send(a); | |
signal.send(b); | |
} | |
test "signal" { | |
const StringSignal = Signal([]const u8); | |
var signal = StringSignal.init(); | |
const message1 = "Hello"; | |
const message2 = "World"; | |
const thread = try std.Thread.spawn(.{}, send2, .{ &signal, message1, message2 }); | |
const recieved1 = signal.recieve(); | |
const recieved2 = signal.recieve(); | |
try std.testing.expect(std.mem.eql(u8, recieved1, message1)); | |
try std.testing.expect(std.mem.eql(u8, recieved2, message2)); | |
thread.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment