Skip to content

Instantly share code, notes, and snippets.

@maxsei
Created June 12, 2023 19:28
Show Gist options
  • Select an option

  • Save maxsei/149460ce42dd08b32fcc88d9dd823f73 to your computer and use it in GitHub Desktop.

Select an option

Save maxsei/149460ce42dd08b32fcc88d9dd823f73 to your computer and use it in GitHub Desktop.
concurrency experimentation in zig 0.11.0-dev.3202+378264d40
const std = @import("std");
const testing = std.testing;
const time = std.time;
const Mutex = std.Thread.Mutex;
var rand = std.rand.DefaultPrng.init(0);
pub fn hi(store: *usize, wg_counter: *usize, m: *Mutex) void {
// const id = std.Thread.getCurrentId();
// std.debug.print("hello from thread: {}\n", .{id});
{
// const variance_ns = 10;
// const amount = rand.random().int(u64) % variance_ns + @as(comptime_int, 1e6);
const amount = @as(comptime_int, 1e6);
time.sleep(amount);
}
// std.debug.print("bye from thread: {}\n", .{id});
store.* += 1; // race conditions
m.lock();
wg_counter.* -= 1;
m.unlock();
}
test {
var elapsed_average: f32 = 0;
var syncronization_checks_average: f32 = 0;
// const check_interval = 1_000_000;
const check_interval = 0;
const runs = 1000;
for (0..runs) |_| {
var store: usize = 0;
const num_threads = 1;
var wg_counter: usize = num_threads;
var m = Mutex{};
const start = time.nanoTimestamp();
for (0..num_threads) |_| {
_ = try std.Thread.spawn(.{ .stack_size = 1024 }, hi, .{ &store, &wg_counter, &m });
}
var syncronization_checks: usize = 0;
while (true) {
// if (check_interval > 0) time.sleep(check_interval);
m.lock();
if (wg_counter == 0) break;
m.unlock();
syncronization_checks += 1;
}
const end = time.nanoTimestamp();
const elapsed = end - start;
// std.debug.print("finished in {}(ns) with {} syncronization checks occuring at an interval of {}(ns)\n", .{ elapsed, syncronization_checks, check_interval });
elapsed_average += @intToFloat(f32, elapsed) / @intToFloat(f32, runs);
syncronization_checks_average += @intToFloat(f32, syncronization_checks) / @intToFloat(f32, runs);
// try testing.expectEqual(@as(@TypeOf(store), num_threads), store);
}
std.debug.print("average finished in {}(ns) with {} syncronization checks occuring at an interval of {}(ns)\n", .{ elapsed_average, syncronization_checks_average, check_interval });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment