12 ms·
Leveraging Zig's Allocators
- _9hey 2y agoHas anyone here used zig with Bazel?
- hansvm 2y agoNot me, not yet, and it's been a few years since I've used Blaze. It ought to be fairly straightforward. Zig is an easy dependency to either vendor or install on a given system/code-base (much more painful currently if you want Blaze to also build Zig itself), and at a bare minimum you could just add BUILD steps for each of the artifacts define in build.zig. Things get more interesting if you want to take advantage of Zig's caching, especially once incremental compilation is fully released. It's a fast enough compilation step that perhaps you could totally ignore Zig's caching for now and wait to see how that feature shapes up before making any hard decisions, but my spidey senses say that'll be a nontrivial amount of work for _somebody_ to integrate those two ideas.
- kristoff_it 2y agoUber has https://github.com/uber/hermetic_cc_toolchain https://github.com/uber/hermetic_cc_toolchain
- deleted 2y ago[deleted]
- lionkor 2y agoI love the way Zig does allocators, when you compare it to Rust where allocation failures just panic (rolls eyes)
- deleted 2y ago[deleted]
- bombela 2y agoIt's getting there eventually! https://doc.rust-lang.org/std/boxed/struct.Box.html#method.try_new https://doc.rust-lang.org/std/boxed/struct.Box.html#method.t...
- hypeatei 2y agoI agree, the lack of control is frustrating but on the contrary: how much software is actually going to do anything useful if allocation is failing? Designing your std library around the common case then gathering input on what memory fallible APIs should look like is smarter IMO.
- hansvm 2y agoMost problems have speed/memory/disk tradeoffs available. Simple coding strategies include "if RAM then do the fast thing, else do the slightly slower thing", "if RAM then allocate that way, else use mmap", "if RAM then continue, else notify operator without throwing away all their work", .... Rust was still probably right to not expose that at first since memory is supposed be fairly transparent, but Zig forces the user to care about memory, and given that constraint it's nearly free to also inform them of problems. The stdlib is already designed (like in Rust) around allocations succeeding, since those errors are just passed to the caller, but Zig can immediately start collecting data about how people use those capabilities. At a language level, including visibility into allocation failures was IMO a good idea.
- kibwen 2y agoThe Rust standard library aborts on allocation failure using the basic APIs, but Rust itself doesn't allocate. If someone wanted to write a Zig-style library in Rust, it would work just fine.
- pcwalton 2y agoStack overflow, which is a type of allocation failure, still aborts in Zig, so it's not that simple.
- anonymoushn 2y agoandrewrk sees this as a failure but doesn't yet have a solution. It seems difficult to provide users with features they want, such as recursion and C interop, while also statically proving the stack is sufficiently small. In programs that don't have stack overflows, it's nice to be able to handle allocation failures though :)
- skybrian 2y agoIs there a reason why someone wouldn't use retain_with_limit or is doing without it just an exercise?
- latch 2y agoThe inspiration for the post came from my httpz library. The fallback using a FixedBufferAllocator + ArenaAllocator is used. The fixed buffer is a thread local. But the arena allocators belong to connections, of which there could be thousands. You might have 1 fixed buffer, for N (500+) ArenaAllocators (but only being used per one at a time). This allows you to allocate a relatively large fixed buffer since you have relatively few threads. If you just used retain_with_limit, then you'd either have to have a much smaller retained size, or you'd need a lot more memory. https://github.com/karlseguin/http.zig/blob/c8b04e3fef5abf324c452f023e6b999c2ab85d6f/src/httpz.zig#L481 https://github.com/karlseguin/http.zig/blob/c8b04e3fef5abf32...
- mikemitchelldev 2y agoOff topic but I wish Go had chosen to use fn rather than func
- ziggy_star 2y agoOh hey, are you that Mitch? I literally just signed up to ask if anybody can recommend any good Zig codebases to read other than Tigerbeatle. How's your terminal going? Edit: The rest of the posted site seems like a treasure trove not just this one article. Was wondering how to get into Zig and here we are. Such kismet. Almost missed it so heads up for others.
- mikemitchelldev 2y agoNo, sorry not me. Though I have signed up for an invite for that terminal by Mitchell Hashimoto (I think his name is).
- slimsag 2y agoWe're working on a game engine in Zig[0] If you're looking for interesting Zig codebases to read, you might be interested in our low-level audio input/output library[1] or our module system[2] codebase - the latter includes an entity component system and uses Zig's comptime to a great degree to enable some interesting flexibility (dependency injection, global view of the world, etc.) while maintaining a great amount of type safety in an otherwise dynamic system. [0] https://machengine.org/ https://machengine.org/ [1] https://github.com/hexops/mach/tree/main/src/sysaudio https://github.com/hexops/mach/tree/main/src/sysaudio [2] https://github.com/hexops/mach/tree/main/src/module https://github.com/hexops/mach/tree/main/src/module
- ziggy_star 2y agoThanks!
- deleted 2y ago[deleted]
- samatman 2y ago
- gizmo 2y agoI'm not 100% sure how Zig allocators work but it looks like the arena memory is getting re-used without zeroing the memory? With slight memory corruption freed memory from a previous request can end up leaking. That's not great. Even if you don't have process isolation between workers (which is generally what you want) then you can still put memory arenas far apart in virtual memory, make use of inaccessible guard pages, and take other precautions to prevent catastrophic memory corruption.
- eknkc 2y agoI guess you could place a zeroing allocator wrapper in between the arena and it's underlying allocator. That would write zero to anything that's getting freed. Arena deinit will free anything allocated from the underlying allocator so upon completion of each request, used memory would be zeroed before returned back to the main allocator. And that handler signature would still be the same. Which is the he whole point of this article so, yay.
- nurpax 2y agoThe same can happen with C malloc/free too.
- KerrAvon 2y agoThat’s not specific to Zig — local heap allocators generally don’t zero deallocated memory — that’s a significant, unnecessary performance hit. If you need data to be isolated when memory is corrupt, you need it to be isolated always.
- 10000truths 2y agomemset is the golden example of an easily pipelined, parallelized, predictable CPU operation - any semi-modern CPU couldn't ask for easier work to do. Zeroing 8 KB of memory is very cheap. If we use a modern Xeon chip as an example, an AVX2 store has a throughput of 2 instructions / cycle. Doing that 256 times for 8 KB totals 128 cycles, plus a few extra cycles to account for the latency of issuing the first instruction and the last store to the L1 cache. With a 2 GHz clock frequency, it still takes less than 70 nanoseconds. For comparison, an integer divide has a worst-case latency of 90ish cycles, or 45ish nanoseconds.
- eknkc 2y agoI think the last sample needs a `fba.reset()` call in between requests. BTW, I used zig a lot recently and the opaque allocator system is great. You can create weird wrappers and stuff. For example, the standard library json parser will parse json, deserialize a type that you requested (say, a struct). But it needs to allocate stuff. So it creates an arena for that specific operation and returns a wrapper that has a `deinit` method. Calling it deinits the arena so you essentially free everything in your graph of structs, arrays etc. And since it receives an upstream allocator for the arena, you could pass in any allocator. A fixed stack allocator if you wish to use stack space, another arena, maybe jemalloc wrapper. A test allocator that checks for memory leaks.. Whatever.
- latch 2y agofixed, thanks.
- hinkley 2y agoWhen I read json I always end up holding onto values from some of the keys. Sometimes the keys too if the node is abstract enough. I assume the receiver then has to know it has to clone all of those values, yes? That seems a little tricky for general code and moreso for unit tests.
- anonymoushn 2y agoYou can pass the json deserializer an allocator that is appropriate for the lifetime of the object you want to get out of it, so often no copying is required.
- saagarjha 2y agoRight, but that means you lose the simplicity and performance benefits of an arena allocator.
- anonymoushn 2y agoI've mainly written unusual code that allocates a bunch of FixedBufferAlocators up front and clears each of them according to their own lifecycles. I agree that more typical code would reach for a GPA or something here. If you're using simdjzon, the tape and strings will be allocated contiguously within a pair of buffers (and then if you actually want to copy from the tape to your own struct containing slices or pointers then you'll have to decide where that goes), but the std json stuff will just repeatedly call whatever allocator you give it.
- ctxcode 2y agoThese kind of tactics work for simple examples. In real world http servers you'll retain memory across requests (caches) and you'll need a way to handle blocking io. That's why most commonly we use GC'd/ownership languages for this + things like goroutines/tokio/etc.. web devs dont want to deal with memory themselfs.
- sph 2y agoOff the top of my head, I was wondering... for software like web services, isn't it easier and faster to use a bump allocator per request, and release the whole block at the end of it? Assuming the number of concurrent requests/memory usage is known and you don't expect any massive spike. I am working on an actor language kernel, and was thinking of adopting the same strategy, i.e. using a very naive bump allocator per actor, with the idea that many actors die pretty quickly so you don't have to pay for the cost of GC most of the time. You can run the GC after a certain threshold of memory usage.
- jerf 2y agoHave you looked at how Erlang does memory management within its processes? You definitely can "get away" with a lot of things when you have actors you can reasonably expect will be small scale, if you are absolutely sure their data dies with them.
- sph 2y agoThe trick to Erlang's memory management is that data is immutable and never shared, so all the complication and contention around GC and atomic locks just disappear.
- mst 2y agoThe key thing (as I understand it) is that each process naturally has a relatively small private set of data, so Erlang can use a stop-the-process semispace copying collection strategy and it's fast enough to work out fine. Since nothing can be writing to it during that anyway, I'm not sure the language level immutability makes a lot of difference to GC itself.
- Jimiliyaa 2y ago[flagged]
- cageface 2y agoI have to admit I don’t really understand the problem Zig is trying to solve. If you’re not trying at the language level to address the core problems of C/C++, like Rust is, then it seems like you’re just making a more ergonomic version of those languages and that’s not enough to overcome how deeply entrenched they are.
- lionkor 2y agoZigs tight C integration makes it easy to just start using Zig in an existing C codebase, which is a great way to overcome the challenges you've mentioned. It doesn't need to replace C all at once, just slowly.
- cageface 2y agoSure but is that really enough to get buy in on a whole new language? Especially when the new language still leaves open the door for so many of the critical problems with C?
- throwawaymaths 2y agoI mean zig really leaves open ONE door, which is temporal memory safety. It is likely that zig will solve this. Rust says you must solve this with the type system. I'm not convinced that is the case.
- kaba0 2y agoAlso, it doesn’t really have a solution. There are safe ways to concurrently access the same memory region, that rust disallows without unsafe, and if you are writing a high-performance language runtime you might well need these features.
- throwawaymaths 2y agoYeah but you'll still need something to live around the high performance features and a mechanism to check temporal memory safety would be nice.