diff --git a/course/basic/define-variable.md b/course/basic/define-variable.md index 8c3a9fae..047a32d0 100644 --- a/course/basic/define-variable.md +++ b/course/basic/define-variable.md @@ -153,3 +153,9 @@ pub usingnamespace @cImport({ > [!IMPORTANT] > 初次阅读此处困惑是正常的,后面的概念学习完成后此处自通。 + +## `threadlocal` + +变量可以使用 `threadlocal` 修饰,来使得该变量在不同线程中是不同的示例: + +<<<@/code/release/define_variable.zig#threadlocal diff --git a/course/code/12/define_variable.zig b/course/code/12/define_variable.zig index a8cbe2cf..6258928c 100644 --- a/course/code/12/define_variable.zig +++ b/course/code/12/define_variable.zig @@ -146,3 +146,26 @@ const Deconstruct = struct { _ = x; } }; + +const ThreadLocal = struct { + // #region threadlocal + const std = @import("std"); + threadlocal var x: i32 = 1234; + + fn main() !void { + const thread1 = try std.Thread.spawn(.{}, testTls, .{}); + const thread2 = try std.Thread.spawn(.{}, testTls, .{}); + testTls(); + thread1.join(); + thread2.join(); + } + + fn testTls() void { + // 1234 + std.debug.print("x is {}\n", .{x}); + x += 1; + // 1235 + std.debug.print("x is {}\n", .{x}); + } + // #endregion threadlocal +}; diff --git a/course/code/14/define_variable.zig b/course/code/14/define_variable.zig index a8cbe2cf..6258928c 100644 --- a/course/code/14/define_variable.zig +++ b/course/code/14/define_variable.zig @@ -146,3 +146,26 @@ const Deconstruct = struct { _ = x; } }; + +const ThreadLocal = struct { + // #region threadlocal + const std = @import("std"); + threadlocal var x: i32 = 1234; + + fn main() !void { + const thread1 = try std.Thread.spawn(.{}, testTls, .{}); + const thread2 = try std.Thread.spawn(.{}, testTls, .{}); + testTls(); + thread1.join(); + thread2.join(); + } + + fn testTls() void { + // 1234 + std.debug.print("x is {}\n", .{x}); + x += 1; + // 1235 + std.debug.print("x is {}\n", .{x}); + } + // #endregion threadlocal +};