-fsanitize-thread

Context:

  • zig version: 0.15.2
  • OS: NixOS, Ubuntu

I’ve been trying to understand how to get the -fsanitize-thread option working and not having a great deal of success.

I have a small example program here that definitely has a race that helgrind happily confirms:

const std = @import(“std”);

var bank_account: i32 = 200;

pub fn main() !void {
    var creditor = try std.Thread.spawn(.{}, credit, .{});
    var debitor = try std.Thread.spawn(.{}, debit, .{});
    creditor.join();
    debitor.join();
    std.debug.print(“balance: ‘{d}’\n”, .{bank_account});
}

pub fn credit() void {
    var i: usize = 0;
    while (i < 1000) : (i += 1) {
        var balance = bank_account;
        balance += 20;
        bank_account = balance;
    }
}

pub fn debit() void {
    var i: usize = 0;
    while (i < 1000) : (i += 1) {
        var balance = bank_account;
        balance -= 20;
        bank_account = balance;
    }
}

When I build this code, I use:

zig build-exe -fsanitize-thread threads.zig

However, when I execute the resulting binary, I’m not seeing any output from TSAN, even when increasing the verbosity.

TSAN_OPTIONS=“verbosity=3” ./threads

Unfortunately, I haven’t been able to find a lot of information online regarding the usage or behavior of this build option. If anybody could offer some suggestions or pointers, I’d greatly appreciate it! :slight_smile:

Did you try -fllvm or -OReleaseSafe?

4 Likes

I hadn’t :man_facepalming: Testing now, each option independently achieves the desired behavior, and it makes sense why.

Thank you! Really appreciate your time!

1 Like