How can I synchronize multiple processes in Erlang?

Viewed 53

I'm thinking about implementing a GPS+I2C inertial measurement system (IMU) in Erlang. I would like to start taking multiple samples from a set of I2C slaves based on the GPS 1PPS mechanism, in order to measure everything at the same time.

Since Erlang uses message queues for receiving messages, what can I do to ensure synchronization between GPS and I2C sensors? Can I handle both in separate processes without losing synchronicity?

1 Answers

How can I synchronize multiple processes in Erlang?

receive
    {Pid1, Data} -> do_something
end,
receive
    {Pid2, Data} -> do_something
end
receive
    {Pid3, Data} -> do_something
end,
...

The first receive will block until data from the process with pid Pid1 sends a message. If the Pid1 process takes the longest to execute, then the subsequent receives will all execute immediately. If the Pid1 process takes the least amount of time to execute, then at least one of the subsequent receives will block.

The overall result is that all the receives will execute in the time it takes for the longest process to finish and send a message.

Related