STM orElse
joeyh at
I recently had to implement a thread-safe wrapper to fcntl locks, which involved implementing my own inter-thread locking code. Because POSIX is horrible. http://git-annex.branchable.com/devblog/day_286-287__rotten_locks/
Take a look at this implementation: http://source.git-annex.branchable.com/?p=source.git;a=blob;f=Utility/LockPool/STM.hs
- First we have the unsafePerformIO of doom on line 46. (Actually safe in this application.)
- But then, look at how nice the implementation of
tryTakeLockis! (line 70) It useswaitTakeLockand converts it from a blocking wait to a one-time try, by simply using theorElsecombinator included in Haskell's STM implementation.
STM is awesome, and the orElse combinator is an awesome improvement on top of it, described in beautiful concurrency:
In particular, blocking (retry) and choice (orElse), which are fundamentally non-modular when expressed using locks, are fully modular in STM.
Mike Linksvayer likes this.