[erlang-questions] time consuming operations inside gen_server
Wed Dec 12 11:28:52 CET 2012
On 12/12/2012 01:27 AM, Martin Dimitrov wrote:
> So, would it be appropriate to create a process that will do the time
> consuming operation and then notify the gen_server?
Yes, processes are cheap in Erlang. There is no reason not to create a separate process for a task, that runs for awhile, to make sure the task doesn't stop your gen_server from processing its message queue. You could do it with a erlang:spawn_link or supervisor:start_child, both of which are typically used in this type of a situation. You want to avoid using erlang:process_flag(trap_exit, true), because it is simpler to have a supervisor manage the process, than have manual, custom supervisor-like functionality (within your gen_server).
There is another reason which long-running tasks often need separate processes, which is a separate concern. If memory is used quickly, in a large quantity, you want the garbage collector to run quickly to free memory for other processes. The short-lived process causes the garbage collector to collect when it dies (all the memory from the task), which would otherwise be a problem in a longer-lived process (since the memory would just accumulate, and would not be collected quickly).
More information about the erlang-questions