Skip to content

Instantly share code, notes, and snippets.

@MgaMPKAy
Created July 11, 2014 10:25
Show Gist options
  • Save MgaMPKAy/99d94135634f171c67c7 to your computer and use it in GitHub Desktop.
Save MgaMPKAy/99d94135634f171c67c7 to your computer and use it in GitHub Desktop.
It's nonsense to compare switches of native thread and green thread (https://ruby-china.org/topics/20367)
import Control.Concurrent
import Control.Monad
import Data.IORef
main = do
c <- newIORef (0::Int)
arr <- newIORef []
replicateM_ 100 $ forkIO $ thread c
replicateM_ 20 $ do
v <- readIORef c
putStrLn $ "c = " ++ show v
when (v /= 0) $ modifyIORef' arr (v:)
writeIORef c 0
threadDelay (10 ^ 6)
a <- readIORef arr
print $ fromIntegral (sum a) `div` length a
thread c = forever $ do
modifyIORef' c (+1)
yield
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment