# Locking allocations

**URL:** <https://ziggit.dev/t/locking-allocations/8172>\
**Category:** Explain\
**Tags:** memory-management, standard-library\
**Created:** [January 26, 2025, 4:22pm UTC](https://ziggit.dev/t/locking-allocations/8172 "2025-01-26T16:22:06Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![vkondratiuk](https://ziggit.dev/user_avatar/ziggit.dev/vkondratiuk/32/3847_2.png) [@vkondratiuk](https://ziggit.dev/u/vkondratiuk)\
**Post date:** [January 26, 2025, 4:22pm UTC](https://ziggit.dev/t/locking-allocations/8172/1 "2025-01-26T16:22:07Z")

</div>

Hey folks!

I’ve been learning more about multithreading and decided to implement ThreadPool from scratch for educational purposes. I’ve used standard library as a reference. The one thing I seem to missunderstand is in the `.spawn()` method:

Why do we lock the mutex before and not after the `Closure` allocation? Isn’t allocating on heap - thread-safe? I thought we would only want to lock the mutex on `run_queue` mutation and thus reduce the critical section

> <https://github.com/ziglang/zig/blob/92b20e42162675d35ffd27845e66b0f9213c00c2/lib/std/Thread/Pool.zig#L245>

---

<div class="post-metadata">

**Author:** ![AndrewKraevskii](https://ziggit.dev/user_avatar/ziggit.dev/andrewkraevskii/32/2564_2.png) [@AndrewKraevskii](https://ziggit.dev/u/AndrewKraevskii)\
**Post date:** [January 26, 2025, 5:05pm UTC](https://ziggit.dev/t/locking-allocations/8172/2 "2025-01-26T17:05:29Z")

</div>

It is only threadsafe if you using threadsafe allocator like `std.heap.GeneralPurposeAllocator` and std.heap.c\_allocator.  
Almost every other allocator in std is not threadsafe.

Also `std.heap.GeneralPurposeAllocator` can be configured to be not thread safe.
