简体   繁体   中英

Task like GPIO read forever should be a recursive function or GenServer?

I am monitoring a value continuously for detection. I am wondering will it work reliably if it is a recursive function? Or I should create a Genserver and call it continuously so that it can handle failures? Which are the best cases for using Genservers and which are not.

A GenServer is also just a recursively called function, but it's running in its own process and has some additional functionality on top.

You'll want to model long-running processes as GenServer for several reasons:

  • Parallelism - if implemented as a GenServer, aka a separate Process, the system will be able to do other things in parallel
  • Isolate errors - if the GPIO code crashes you don't want to affect the rest of the system
  • Supervision - having a GenServer allows the system to re-start on failures. It also gives you the ability to define other processes that depend on the GPIO process, eg consumers of the data.

I recommend reading the chapter "Working with Multiple Processes" from "Programming Elixir" by Dave Thomas to learn more about processes etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM