Skip to content

Commit d0efc2c

Browse files
committed
docs: 增加 threadlocal 讲解
1 parent c281392 commit d0efc2c

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

course/basic/define-variable.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,9 @@ pub usingnamespace @cImport({
153153

154154
> [!IMPORTANT]
155155
> 初次阅读此处困惑是正常的,后面的概念学习完成后此处自通。
156+
157+
## `threadlocal`
158+
159+
变量可以使用 `threadlocal` 修饰,来使得该变量在不同线程中是不同的示例:
160+
161+
<<<@/code/release/define_variable.zig#threadlocal

course/code/12/define_variable.zig

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,3 +146,26 @@ const Deconstruct = struct {
146146
_ = x;
147147
}
148148
};
149+
150+
const ThreadLocal = struct {
151+
// #region threadlocal
152+
const std = @import("std");
153+
threadlocal var x: i32 = 1234;
154+
155+
fn main() !void {
156+
const thread1 = try std.Thread.spawn(.{}, testTls, .{});
157+
const thread2 = try std.Thread.spawn(.{}, testTls, .{});
158+
testTls();
159+
thread1.join();
160+
thread2.join();
161+
}
162+
163+
fn testTls() void {
164+
// 1234
165+
std.debug.print("x is {}\n", .{x});
166+
x += 1;
167+
// 1235
168+
std.debug.print("x is {}\n", .{x});
169+
}
170+
// #endregion threadlocal
171+
};

course/code/14/define_variable.zig

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,3 +146,26 @@ const Deconstruct = struct {
146146
_ = x;
147147
}
148148
};
149+
150+
const ThreadLocal = struct {
151+
// #region threadlocal
152+
const std = @import("std");
153+
threadlocal var x: i32 = 1234;
154+
155+
fn main() !void {
156+
const thread1 = try std.Thread.spawn(.{}, testTls, .{});
157+
const thread2 = try std.Thread.spawn(.{}, testTls, .{});
158+
testTls();
159+
thread1.join();
160+
thread2.join();
161+
}
162+
163+
fn testTls() void {
164+
// 1234
165+
std.debug.print("x is {}\n", .{x});
166+
x += 1;
167+
// 1235
168+
std.debug.print("x is {}\n", .{x});
169+
}
170+
// #endregion threadlocal
171+
};

0 commit comments

Comments
 (0)