| Safe Haskell | None |
|---|---|
| Language | Haskell2010 |
Hmssql.Connection.Locking
Description
A reentrant mutex, so the thread that owns a connection's active response can issue another request (which cancels the first) without deadlocking.
The owner is recorded by its thread number, not its ThreadId. Holding
a ThreadId would keep the owner's thread object reachable from the
connection, so an owner that blocks forever (on an MVar nobody else can
fill, say) could never be found unreachable by the garbage collector: it
would not receive BlockedIndefinitelyOnMVar, never
release the mutex, and every other user of the connection would hang with
it. hpgsql uses a weak ThreadId for the same reason; a number also works
after the collector has declared the thread dead but resurrected it to run
its exception handlers, which may re-enter the mutex (a rollback, say).
Adapted from Hpgsql.Locking in hpgsql
(https://github.com/mzabani/hpgsql), Copyright Marcelo Zabani (c) 2026,
BSD-3-Clause.
Documentation
withMutex :: Mutex -> IO a -> IO a Source #
Run the action holding the mutex, waiting for any other owner to leave. Waiting is interruptible; the mutex is released however the action ends.
Reentry takes a fast path: when this thread holds the mutex already, the
action just runs. Nothing needs undoing afterwards, since the entry that
took the mutex releases it, and nothing can change the owner under us:
only the owner writes the variable while it is owned. This saves two
STM transactions and an exception frame on every nested use (every token
read inside query, say).