Understanding sending messages to processes

I have following simple test code to try how to send messages between process.

The way I understand my code is :

  1. I spawn 2 separate processes
  2. Processes are executing functions where they should be awaiting a message
  3. In parent process I send a message to each process
  4. Processes should receive them and IO.puts message

What is happening is that nothing is in output and it looks as though program is executing but nothings happening. I have to cntrl+C out of it.

What am I doing wrong?

defmodule Test do
    def startGame() do
        hValue = 1
        dValue = 2

        parent = self()
        hPID = spawn humanTurn(hValue, parent)
        dPID = spawn dealerTurn(dValue, parent)

        send(hPID, {:parent, dValue})
        send(dPID, {:parent, dValue})

    def dealerTurn(dValue, parent) do
        receive do
            {:parent, msg} -> IO.puts(msg)

    def humanTurn(hValue, parent) do
        receive do
            {:parent, msg} -> IO.puts(msg)


You need to pass a function to spawn:

hPID = spawn fn -> humanTurn(hValue, parent) end
dPID = spawn fn -> dealerTurn(dValue, parent) end

If you call spawn humanTurn(hValue, parent) you are executing the humanturn function before the “spawn” call, so it blocks in the first spawn

Thank you!
I got a step further :slight_smile:

´working now

1 Like