Is Core Nano_mutex a replacement for Mutex from stdlib when using core
?
That’s the idea. Nano_mutex
will fall back on Mutex
if there is any contention, but when uncontended, Nano_mutex
is much faster to lock and unlock (check out the newer documentation for some benchmarks).
I wouldn’t call it a replacement; based on my understanding of its docs, you couldn’t, for example, share the mutex between processes with mmap and expect it to work.
I’m not familiar with sharing mutexes across processes, but indeed, the documentation warns: “A nano-mutex is a lightweight mutex that can be used only within a single OCaml runtime.” It relies on the OCaml runtime lock for certain guarantees about where context switches can happen, here for example.
It’s appropriate for controlling access to some data structures between multiple Async/Lwt threads, but I guess not across processes.
By process do you mean forking?
Do we need mutexes on async/lwt threads? I thought the whole point of these monadic concurrency is that we don’t need these lock/unlock mechanisms. No??
It does not necessarily have to be a forked process, and forking by itself is not enough to share a mutex between two processes. You have to put the mutex in a region of memory that is shared between the processes. I don’t think this is a very common thing to do, so IMO Nano_mutex is a good replacement for all sane uses of Mutex .
Ah, you’re right, that was misleading. Nano_mutex
is used in the Async scheduler itself to control access to its internal data structures by multiple threads which might be running at the same time (as in, actual Thread.t
s). It wouldn’t be necessary to use it in your own Async/Lwt programs, if I understand correctly.