Created
January 8, 2014 02:49
-
-
Save myuon/8310959 to your computer and use it in GitHub Desktop.
Haskellでマルチスレッド処理 ref: http://qiita.com/myuon_myon/items/d0334317f220dfe05092
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
forkIO :: IO () -> IO ThreadId -- IO ()を渡すとその場で実行 | |
killThread :: ThreadId -> IO () -- 指定のThreadをkillする | |
threadDelay :: Int -> IO () -- スレッドを指定の時間[microsec]だけ停止する | |
data MVar a -- スレッド内で使えるmutableな変数 | |
newMVar :: a -> IO (MVar a) -- 変数を初期化 | |
takeMVar :: MVar a -> IO a -- 変数の値を取り出す | |
putMVar :: MVar a -> a -> IO () -- 変数に代入する |
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.Concurrent | |
import Control.Monad | |
waiting :: Int -> IO () | |
waiting n = do | |
putStrLn $ "waiting" ++ (replicate n '.') | |
threadDelay 100000 | |
waiting (n+1) | |
doSth :: IO Bool | |
doSth = do | |
-- do something | |
threadDelay 3000000 | |
putStrLn $ "=========== done =========" | |
threadDelay 3000000 | |
putStrLn $ "=========== done =========" | |
threadDelay 3000000 | |
putStrLn $ "=========== done =========" | |
return True | |
ex1 = do | |
w <- forkIO $ waiting 0 | |
u <- doSth | |
when u $ killThread w | |
putStrLn "killed the waiting thread" |
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.Concurrent | |
import Control.Monad | |
waiting :: Int -> IO () | |
waiting n = do | |
putStrLn $ "waiting" ++ (replicate n '.') | |
threadDelay 100000 | |
waiting (n+1) | |
doSthWithMVar :: MVar Bool -> IO () | |
doSthWithMVar ref = do | |
threadDelay 3000000 | |
putStrLn $ "=========== done =========" | |
threadDelay 3000000 | |
putStrLn $ "=========== done =========" | |
threadDelay 3000000 | |
putStrLn $ "=========== done =========" | |
putMVar ref True | |
ex2 = do | |
ref <- newMVar False | |
w <- forkIO $ waiting 0 | |
_ <- forkIO $ doSthWithMVar ref | |
go ref w | |
where | |
go :: MVar Bool -> ThreadId -> IO () | |
go ref w = do | |
tf <- takeMVar ref | |
case tf of | |
True -> do | |
killThread w | |
putStrLn "killed the waiting thread" | |
False -> go ref w |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment