Created
May 28, 2013 21:48
-
-
Save NicolasT/5666429 to your computer and use it in GitHub Desktop.
Using Haskell STM to pick items from multiple sources with bias / priority
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Control.Monad (forever, forM_) | |
| import Control.Concurrent | |
| import Control.Concurrent.STM | |
| data Event = Timeout | |
| | Message Int | |
| deriving (Show) | |
| pusher :: TChan Event -> IO () | |
| pusher c = forM_ [0 ..] $ \i -> do | |
| atomically $ writeTChan c (Message i) | |
| threadDelay $ 600 * 1000 | |
| timeouter :: TMVar Event -> IO () | |
| timeouter t = forever $ do | |
| -- Use tryPutTMVar, since when the previous timeout hasn't been handled | |
| -- yet, we don't really care about setting a new one | |
| atomically $ tryPutTMVar t Timeout | |
| threadDelay $ 1000 * 1000 | |
| reader :: TMVar Event -> TChan Event -> IO () | |
| reader t q = forever $ do | |
| -- Switching sides of orElse would change priority | |
| e <- atomically $ takeTMVar t `orElse` readTChan q | |
| print e | |
| main :: IO () | |
| main = do | |
| t <- newEmptyTMVarIO | |
| q <- newTChanIO | |
| forkIO $ timeouter t | |
| forkIO $ pusher q | |
| forkIO $ reader t q | |
| forever $ threadDelay $ 1000 * 1000 |
Author
NicolasT
commented
May 28, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment