Last active
August 29, 2015 14:12
-
-
Save EarlGray/b2d1273d696ca40a4392 to your computer and use it in GitHub Desktop.
sleepsort
This file contains 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
-module(sleepsort). | |
-export([sleepsort/1, sleepsort/2]). | |
timer(Val, Pid, Quality) -> | |
receive after Quality * Val -> Pid ! Val end. | |
gather(Acc, N, Max) when N + 1 > Max -> lists:reverse(Acc); | |
gather(Acc, N, Max) -> receive Val -> gather([Val | Acc], N + 1, Max) end. | |
sort([], N, _) -> | |
gather([], 0, N); | |
sort([Val | Arr], N, Quality) -> | |
Me = self(), | |
spawn(fun () -> timer(Val, Me, Quality) end), | |
sort(Arr, N + 1, Quality). | |
sleepsort(Arr) -> sort(Arr, 0, 18). | |
sleepsort(Arr, Quality) -> sort(Arr, 0, Quality). |
This file contains 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
module SleepSort (sleepsort) where | |
import Control.Concurrent | |
import Control.Concurrent.STM | |
worker chan timefun val = do | |
threadDelay $ timefun val | |
atomically $ writeTChan chan val | |
sleepsort :: (a -> Int) -> [a] -> IO [a] | |
sleepsort timefun arr = do | |
chan <- newTChanIO | |
mapM_ (forkIO . worker chan timefun) arr | |
mapM (\_ -> atomically $ readTChan chan) [1 .. length arr] |
This file contains 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
module SleepSortBar (sleepsort) where | |
import Control.Concurrent | |
import Control.Concurrent.STM | |
--- Barriers | |
type Barrier a = MVar a | |
newBarrier :: IO (Barrier a) | |
newBarrier = newEmptyMVar | |
signalBarrier :: Barrier a -> a -> IO () | |
signalBarrier = putMVar | |
waitBarrier :: Barrier a -> IO a | |
waitBarrier = readMVar | |
--- Sleepsort | |
worker bar chan timefun val = do | |
waitBarrier bar | |
threadDelay $ timefun val | |
atomically $ writeTChan chan val | |
sleepsort :: (a -> Int) -> [a] -> IO [a] | |
sleepsort timefun arr = do | |
bar <- newBarrier | |
chan <- newTChanIO | |
mapM_ (forkIO . worker bar chan timefun) arr | |
signalBarrier bar () | |
mapM (\_ -> atomically $ readTChan chan) [1 .. length arr] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment