A Tour of Go in Haskell

GitHub Language
sync.Mutex

Channel is a useful tool for communication between lightweight threads. But there are other kind of communications which are impossible (or hard) to be solved by channel. For example, a case that threads share a variable and modify it without conflicts.

Go provides traditional Mutex for the problem. We can use TVar in the STM toolbox on Haskell. TVar solve the problem directly compared to Mutex. The usage is similar to TQueue.

var <- newTVar x     -- make new TVar storing x
x <- readTvar var    -- read current value from TVar
modifyTVar var func  -- modify TVar by func lazily
modifyTVar' var func -- modify TVar by func strictly

The sample code on the right side composes a counter which is safely modified by multiple threads by using TVar. Because the atomically of STM makes a transaction (indivisible section), modifying counter do not cause conflicts.

< 9 / 11 >