Trying to understand the simple things of Haskell STM

I am stuck in understanding atomically in STM.

I illustrate an example

import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import qualified Data.Map as Map 

main :: IO ()
main =  do
    d <- atomically$ newTVar Map.empty
    sockHandler  d 

sockHandler ::  TVar (Map.Map String Int)-> IO ()
sockHandler  d = do
    forkIO $ commandProcessor  d 1
    forkIO $ commandProcessor  d 2
    forkIO $ commandProcessor  d 3
    forkIO $ commandProcessor  d 4
    forkIO (threadDelay 1000 >> putStrLn "Hello World?")

    threadDelay 10000
    return ()

commandProcessor ::  TVar (Map.Map String Int)-> Int-> IO ()
commandProcessor  d i= do
  addCommand d i
  commandProcessor  d i 

addCommand  ::  TVar (Map.Map String Int) ->Int -> IO ()
addCommand    d i = do
  succ <- atomically $ runAdd d
  putStrLn  $"Result of add in " ++ (show i)++ " " ++( show succ)

runAdd  d =do
  dl <- readTVar d
  let (succ,g)= if   Map.member "a" dl
                  then
                      (False,dl)
                  else
                      (True,Map.insert "a" 9 dl)
  writeTVar d g
  return succ

The result of the selection will be like this:

Result of adding to 1 True Result of adding in 4 False Result of adding to 1 FalseResult add to 2 FalseResult of add to 3 False Hello World? Result add 4 false

Result of adding in 1 FalseResult of adding in 2 False Result of adding in 3 False Result of adding in 4 False

Result of adding to 1 False Result of adding to 2 FalseResult add to 3 FalseResult add to 4 False

Result of adding to 1 False Result of adding to 2 FalseResult add to 3 FalseResult add to 4 False

Result of adding to 1 False Result of adding to 2 FalseResult add to 4 FalseResult add in 3 False

Result of adding in 1 False Result of adding in 4 FalseResult add in 2 FalseResult add in 3 False

1 FalseResult in 4 False 2 False 3 False

1 FalseResult in 4 False

2 FalseResult in 3 False

1 FalseResult in 4 False

2 FalseResult in 3 False add in 1 False 4 False

2 FalseResult in 3 False

1 FalseResult in 4 False

. , , - , , , , , . , , .

, "" succ ?  succ < - atomically $runAdd d putStrLn $" " ++ ( i) ++ "" ++ (show succ)

" ? i" ( " " )

+3
2

, , . , atomically :

atomically action = do varState <- getStateOfTVars
                       (newState, ret) <- runTransactionWith action varState
                       success <- attemptToCommitChangesToTVars newState
                       if success
                         then return ret
                         else atomically action -- try again

. - , , . STM , , , .

+7
  • threadDelay (), return () after
  • newTVarIO - atomically . newTVar.
  • , forever , commandProcessor.

, "". live-lock, , . , expensive cheap. atomically TVar, , expensive . SO.

, , STM , putStrLn , .

+2

Source: https://habr.com/ru/post/1789441/


All Articles