Skip to content

Commit

Permalink
feat: add thread pool
Browse files Browse the repository at this point in the history
  • Loading branch information
jiacai2050 committed Jan 4, 2025
1 parent b1a66ec commit cc8f8cc
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 0 deletions.
6 changes: 6 additions & 0 deletions book-src/01-04-file-exists.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Check file existence

In this example, we use `panic` to ensure `build.zig` should exist.
```zig
{{#include ../src/01-04.zig}}
```
12 changes: 12 additions & 0 deletions book-src/07-03-threadpool.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
## Thread pool

Thread pools address two different problems:
1. They usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and
2. They provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks.


In this example, we spawn 10 tasks into thread pool, and use `WaitGroup` to wait for them to finish.

```zig
{{#include ../src/07-03.zig}}
```
2 changes: 2 additions & 0 deletions book-src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- [Read file line by line](./01-01-read-file-line-by-line.md)
- [Mmap file](./01-02-mmap-file.md)
- [Find Files modified in the last 24 hours](./01-03-file-modified-24h-ago.md)
- [Check file existence](./01-04-file-exists.md)

- [Cryptography]()

Expand Down Expand Up @@ -36,6 +37,7 @@

- [Explicit Threads](./07-01-spawn.md)
- [Shared Data](./07-02-shared-data.md)
- [Thread pool](./07-03-threadpool.md)

- [Operating System]()

Expand Down
13 changes: 13 additions & 0 deletions src/01-04.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
//! Check file existence

const std = @import("std");
const fs = std.fs;

pub fn main() void {
const filename = "build.zig";
fs.cwd().access(filename, .{}) catch {
std.debug.panic("{s} not exists", .{filename});
};

std.debug.print("{s} exists", .{filename});
}
27 changes: 27 additions & 0 deletions src/07-03.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const std = @import("std");
const print = std.debug.print;

pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();

var pool: std.Thread.Pool = undefined;
try pool.init(.{
.allocator = allocator,
.n_jobs = 4,
});
defer pool.deinit();

var wg: std.Thread.WaitGroup = .{};
for (0..10) |i| {
pool.spawnWg(&wg, struct {
fn run(id: usize) void {
print("I'm from {d}\n", .{id});
}
}.run, .{i});
}
wg.wait();

print("All threads exit.\n", .{});
}

0 comments on commit cc8f8cc

Please sign in to comment.