- Create a new project called master-slave with the simple stack template:
stack new master-slave simple
- Add a dependency on the distributed-process and distributed-process-localnet libraries in the build-depends sub-section of the executable section:
executable master-slave hs-source-dirs: src main-is: Main.hs default-language: Haskell2010 build-depends: base >= 4.7 && < 5 , distributed-process , distributed-process-simplelocalnet
- Note that you might have to add the dependent library specifically to the extra-deps section, as these libraries are not part of stackage LTS at the time of writing this recipe. Add the following to stack.yaml:
extra-deps: - distributed-process-0.6.6 - distributed-process-simplelocalnet-0.2.3.3 - syb-0.6
- Open src/Main.hs. We will be adding our source here. Add the Main module, and the relevant imports:
module Main where import System.Environment (getArgs) import Control.Distributed.Process import Control.Distributed.Process.Node import Control.Distributed.Process.Backend.SimpleLocalnet
- Create the Process that we will run on the master node:
masterTask :: Backend -> [NodeId] -> Process () masterTask backend slaves = do liftIO $ putStrLn $ "Initial slaves: " ++ show slaves terminateAllSlaves backend
- Use main to start either the master or slave node:
main :: IO () main = do args <- getArgs case args of "-m":h:p:[] -> do backend <- initializeBackend h p initRemoteTable startMaster backend (masterTask backend) "-s":h:p:[] -> do backend <- initializeBackend h p initRemoteTable startSlave backend
- Build and execute the project:
stack build stack exec -- master-slave -s 127.0.0.1 10501 & stack exec -- master-slave -s 127.0.0.1 10502 & stack exec -- master-slave -s 127.0.0.1 10503 & stack exec -- master-slave -s 127.0.0.1 10504 & stack exec -- master-slave -m 127.0.0.1 10505
You should see the following output:
