forked from zigbyexample/zigbyexample.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutex.md
46 lines (36 loc) · 832 Bytes
/
mutex.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
---
layout: default
title: Mutex
nav_order: 8
permalink: /mutex
---
[mutex.zig](src/mutex.zig)
```zig
const std = @import("std");
const ThreadSafeCounter = struct {
lock: std.Thread.Mutex,
count: usize,
pub fn increase(self: *ThreadSafeCounter, n: u32) void {
var i: u32 = 0;
while (i < n) : (i += 1) {
self.lock.lock();
defer self.lock.unlock();
self.count += 1;
}
}
};
test {
var threads: [3]std.Thread = undefined;
var counter = ThreadSafeCounter{
.lock = .{},
.count = 0,
};
for (threads) |*thrd| {
thrd.* = try std.Thread.spawn(.{}, ThreadSafeCounter.increase, .{ &counter, 1000 });
}
for (threads) |thrd| {
thrd.join();
}
try std.testing.expect(counter.count == 3_000);
}
```