package eio
Install
dune-project
Dependency
Authors
Maintainers
Sources
sha256=3792e912bd8d494bb2e38f73081825e4d212b1970cf2c1f1b2966caa9fd6bc40
sha512=4a80dbcf8cf2663bdad0f2970871844f37bd293c56bd1ce602910e0a613754945f1f942719f9630906453be7c73c1732dc97526c6c90b0b36100d04fd5e871e4
doc/eio/Eio/Mutex/index.html
Module Eio.MutexSource
Mutual exclusion.
A mutex can be used to ensure that only one piece of code can access a shared resource at one time.
Unlike Stdlib.Mutex, which blocks the whole domain while waiting to take the mutex, this module allows other Eio fibers to run while waiting. You should use this module if your critical section may perform blocking operations, while Stdlib.Mutex may be more efficient if the lock is held only briefly and the critial section does not switch fibers.
Note that mutexes are often unnecessary for code running in a single domain, as the scheduler will only switch to another fiber if you perform an operation that can block.
The type for a concurrency-friendly mutex.
Raised if you attempt to use a mutex that has been disabled.
use_rw ~protect t fn waits for the mutex to be free and then executes fn () while holding the mutex locked. fn may mutate the resource protected by the mutex, but must ensure the resource is in a consistent state before returning. If fn raises an exception, the mutex is disabled and cannot be used again.
use_ro t fn is like use_rw ~protect:false, but if fn raises an exception it unlocks the mutex instead of disabling it. Use this if you only need read-only access to the mutex's resource and so know that it will be in a consistent state even if an exception is raised.
Note: a mutex still only allows one fiber to have the mutex locked at a time, even if all operations are "read-only".
Low-level API
Care must be taken when locking a mutex manually. It is easy to forget to unlock it in some cases, which will result in deadlock the next time a fiber tries to use it. In particular, you need to consider:
- What happens if your critical section raises an exception.
- What happens if your fiber is cancelled while in its critical section.
Lock the given mutex. Only one fiber can have the mutex locked at any time. A fiber that attempts to lock a mutex already locked by another fiber will suspend until the other fiber unlocks the mutex. If no other fiber has the lock, this returns immediately without switching fibers.