Locking allocations

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

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.

2 Likes