A Channel is a link between two processes for sending messages. A process identifier (PID) lets another process connect to a running process or lets a process wait for an incoming connection. section 15.1.2
A basic channel exchange follows these steps:
- Use spawn to start a process and obtain its PID. section 15.1.2
- Use connect with the PID, or listen to wait for another process to connect. section 15.1.2
- Use unsafeSend and unsafeRecv to exchange messages on the channel. section 15.1.2
A request-and-reply adder
A main process sends Add 2 3 to an adder process and receives the Nat result, 5. The adder listens for a connection, handles a request, replies, and waits again. section 15.1.2
main : IO () main = do Just adder_id <- spawn adder | Nothing => putStrLn "Spawn failed" Just chan <- connect adder_id | Nothing => putStrLn "Connection failed" ok <- unsafeSend chan (Add 2 3) #1 Just answer <- unsafeRecv Nat chan #2 | Nothing => putStrLn "Send failed" printLn answer #3
Inspect the main process's channel exchange: it sends an addition request, receives a Nat reply, and prints the answer. section 15.1.2
The primitive operations do not guarantee that processes agree on message types or coordinate their sends and receives. Receiving a String when the sender replies with a Nat can crash; sending a second request can block if the other process handles only one message. Channels can serve as primitives for a separate, type-safe communication protocol. section 15.1.3
