Zig 是怎麼管理內存的
Zig 的內存管理方案
Zig 在內存管理方面採取了類似 C 的方案,完全由程序員管理內存,這也是爲什麼 zig 沒有運行時開銷的原因,同時這也是爲什麼 zig 可以在如此多環境(包括實時軟件、操作系統內核、嵌入式設備和低延遲服務器)中無縫工作的原因。
事實上,在 C 開發中最難以調試的 bug 往往是由於錯誤的內存管理引起的, zig 在此基礎上給我們提供了少量的保護,但僅僅是少量的保護,這就要求程序員在需要明白數據在內存中真實存在的模樣(這就涉及到計算機組成原理和操作系統的理論知識了,當然還涉及到一點點的彙編知識)。
事實上,zig 本身的標準庫爲我們提供了多種內存分配模型:
-
GeneralPurposeAllocator
[1] -
FixedBufferAllocator
[2] -
ArenaAllocator
[3] -
HeapAllocator
[4] -
c_allocator
[5] -
page_allocator
[6]
除了這六種內存分配模型外,還提供了內存池的功能 MemoryPool
[7]
你可能對上面的多種內存模型感到很迷惑,C 語言中不就是 malloc
嗎,怎麼到這裏這麼多的 “模型”,這些模型均有着不同的特點,而且它們之間有一部分還可以疊加使用,zig 在這方面提供了更多的選擇,而且不僅僅是這些,你還可以自己嘗試實現一個內存模型。
原文地址:https://zigcc.github.io/zig-course/advanced/memory_manage.html
Zig 實戰:按行讀取文件
const std = @import("std");
const fs = std.fs;
const print = std.debug.print;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const file = try fs.cwd().openFile("tests/zig-zen.txt", .{});
defer file.close();
// Wrap the file reader in a buffered reader.
// Since it's usually faster to read a bunch of bytes at once.
var buf_reader = std.io.bufferedReader(file.reader());
const reader = buf_reader.reader();
var line = std.ArrayList(u8).init(allocator);
defer line.deinit();
const writer = line.writer();
var line_no: usize = 1;
while (reader.streamUntilDelimiter(writer, '\n', null)) : (line_no += 1) {
// Clear the line so we can reuse it.
defer line.clearRetainingCapacity();
print("{d}--{s}\n", .{ line_no, line.items });
} else |err| switch (err) {
error.EndOfStream => {}, // Continue on
else => |e| return e, // Propagate error
}
}
原文地址:https://zigcc.github.io/zig-cookbook/01-01-read-file-line-by-line.html
參考資料
[1]
GeneralPurposeAllocator
: https://ziglang.org/documentation/master/std/#A;std:heap.GeneralPurposeAllocator
[2]
FixedBufferAllocator
: https://ziglang.org/documentation/master/std/#A;std:heap.FixedBufferAllocator
[3]
ArenaAllocator
: https://ziglang.org/documentation/master/std/#A;std:heap.ArenaAllocator
[4]
HeapAllocator
: https://ziglang.org/documentation/master/std/#A;std:heap.HeapAllocator
[5]
c_allocator
: https://ziglang.org/documentation/master/std/#A;std:heap.c_allocator
[6]
page_allocator
: https://ziglang.org/documentation/master/std/#A;std:heap.page_allocator
[7]
MemoryPool
: https://ziglang.org/documentation/master/std/#A;std:heap.MemoryPool
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/nhdV9O1vtnKtptWf6efxxQ