Created
July 25, 2012 09:33
-
-
Save billdozr/3175290 to your computer and use it in GitHub Desktop.
Simple distributed Ping
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
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable, GeneralizedNewtypeDeriving #-} | |
module Main where | |
import System.Environment (getArgs, getProgName) | |
import Data.Typeable | |
import Data.Binary | |
import Control.Concurrent (threadDelay) | |
import Control.Distributed.Process.Backend.SimpleLocalnet | |
import Control.Distributed.Process | |
import Control.Distributed.Process.Node hiding (newLocalNode) | |
import Control.Distributed.Process.Closure | |
newtype Ping = Ping ProcessId | |
deriving (Typeable, Binary, Show) | |
newtype Pong = Pong ProcessId | |
deriving (Typeable, Binary, Show) | |
worker :: Ping -> Process () | |
worker (Ping master) = do | |
wId <- getSelfPid | |
say "Got a Ping!" | |
send master (Pong wId) | |
remotable ['worker] | |
initialProcess :: String -> Backend -> [NodeId] -> Process () | |
initialProcess "WORKER" backend peers = do | |
say $ "Peers: " ++ show peers | |
pid <- getSelfPid | |
register "slaveController" pid | |
receiveWait [] | |
initialProcess "MASTER" backend workers = do | |
say $ "Workers: " ++ show workers | |
pid <- getSelfPid | |
mapM_ (\w -> do | |
say $ "Sending a Ping to " ++ (show w) ++ "..." | |
spawn w ($(mkClosure 'worker) (Ping pid))) workers | |
say $ "Waiting for reply from " ++ (show (length workers)) ++ " worker(s)" | |
mapM_ (\_ -> do | |
let resultMatch = match (\(Pong wId) -> return wId) | |
in do wId <- receiveWait [resultMatch] | |
say $ "Got back a Pong from " | |
++ (show $ processNodeId wId) ++ "!") workers | |
(liftIO . threadDelay) 2000000 -- Wait a bit before return | |
main = do | |
prog <- getProgName | |
args <- getArgs | |
case args of | |
["master", host, port] -> do | |
backend <- initializeBackend host port (__remoteTable initRemoteTable) | |
startMaster backend (initialProcess "MASTER" backend) | |
["worker", host, port] -> do | |
backend <- initializeBackend host port (__remoteTable initRemoteTable) | |
node <- newLocalNode backend | |
peers <- findPeers backend 50000 | |
runProcess node (initialProcess "WORKER" backend peers) | |
_ -> | |
putStrLn $ "usage: " ++ prog ++ " (master | worker) host port" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment