STM
This expands on request suspension in
Scotty with MVar
by replacing MVar
, which
can result in deadlocks, with STM
.
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad.Trans (liftIO)
import qualified Control.Concurrent.STM as STM
import qualified Control.Monad.Trans.Class as Class
import qualified Data.Text.Lazy as TL
import qualified Web.Scotty as Scotty
main :: IO ()
= do
main <- STM.newTVarIO (Nothing :: Maybe String)
sem 3000 $ do
Scotty.scotty "/suspend" $ do
Scotty.get <- liftIO $ STM.atomically $ do
key <- STM.readTVar sem
keyM case keyM of
Nothing -> STM.retry
Just key -> STM.writeTVar sem Nothing >> return key
$ TL.concat $ [ "Resumed with \""
Scotty.text
, TL.pack key"\"."
,
]"/resume/:key" $ do
Scotty.get <- Scotty.param "key"
key $ STM.atomically $ STM.writeTVar sem $ Just key
liftIO $ TL.concat $ [ "Resuming with \""
Scotty.text
, TL.pack key"\"."
, ]