Skip to content

Add example for threadsafe logging. #40

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions outputs/threadsafe-logging.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
λ> :main
Do Re Mi
Fa Sol
La Ti Do
Fa SolL
Dao TRie DMoi

Fa Sol
La Ti Do
Do Re Mi
Do Re Mi
Fa Sol
FaD LoSa o RlTe
i MDio

La Ti Do

λ> import System.Environment (setEnv)

λ> setEnv "MAX_QUEUE" "100"

λ> :main
Fa Sol
La Ti Do
Do Re Mi
La Ti Do
Fa Sol
Do Re Mi
Fa Sol
Do Re Mi
La Ti Do
La Ti Do
Do Re Mi
Fa Sol
Fa Sol
Do Re Mi
La Ti Do
50 changes: 50 additions & 0 deletions threadsafe-logging.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import Control.Concurrent (forkIO, threadDelay)
import Control.Monad.STM (atomically)
import Data.Foldable (for_)
import System.Environment (lookupEnv)
import System.Random (randomRIO)
import Text.Read (readMaybe)

import qualified Control.Concurrent.STM.TBQueue as TBQ


seconds n = 1000000 * n


threadsafeLog maxQueue = do
queue <- atomically (TBQ.newTBQueue maxQueue)

let
logToQueue msg = atomically (TBQ.writeTBQueue queue msg)

printFromQueue = do
threadDelay (seconds 1 `div` 2)
emptyQueue <- atomically (TBQ.isEmptyTBQueue queue)
if emptyQueue then
return ()
else do
msg <- atomically (TBQ.readTBQueue queue)
putStrLn msg
printFromQueue

return (logToQueue, printFromQueue)


sing phrase log =
for_ [1..5] $ \n -> do
i <- randomRIO (1, 10000)
threadDelay (seconds 1 `div` i + n)
log phrase


main = do
(log, print) <- do
maxQueue <- (readMaybe =<<) <$> lookupEnv "MAX_QUEUE"
case maxQueue of
Nothing -> return (putStrLn, threadDelay (seconds 3))
Just n -> threadsafeLog n

for_ [sing "Do Re Mi", sing "Fa Sol", sing "La Ti Do"] $
\singPhrase -> forkIO (singPhrase log)

print