forked from elm/compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBackgroundWriter.hs
42 lines (29 loc) · 907 Bytes
/
BackgroundWriter.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
{-# LANGUAGE BangPatterns #-}
module BackgroundWriter
( Scope
, withScope
, writeBinary
)
where
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar (MVar, newEmptyMVar, newMVar, putMVar, takeMVar)
import qualified Data.Binary as Binary
import Data.Foldable (traverse_)
import qualified File
-- BACKGROUND WRITER
newtype Scope =
Scope (MVar [MVar ()])
withScope :: (Scope -> IO a) -> IO a
withScope callback =
do workList <- newMVar []
result <- callback (Scope workList)
mvars <- takeMVar workList
traverse_ takeMVar mvars
return result
writeBinary :: (Binary.Binary a) => Scope -> FilePath -> a -> IO ()
writeBinary (Scope workList) path value =
do mvar <- newEmptyMVar
_ <- forkIO (File.writeBinary path value >> putMVar mvar ())
oldWork <- takeMVar workList
let !newWork = mvar:oldWork
putMVar workList newWork