How can I tell a specific process (let’s call it the generator) to create a new process in Erlang?
Also, how can I keep track of all the processes that the generator has created?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Okay. Now, for purposes of learning, lets do a very basic example. Others will talk of
OTP Supervisors, Process dictionariese.t.c. but i want to keep it easy for learning purposes. With tis example, the generator can know how many processes it has created, theirPids, knows when they die e.t.c.Testing in shell
E:\Applications>erl Eshell V5.9 (abort with ^G) 1> c(generator). {ok,generator} 2> generator:start(). ok 3> generator:create(generator,child_loop,[]). ok 4> [generator:create(generator,child_loop,[]) || _ <- lists:seq(1,5)],ok. ok 5> generator:send_to_kids("Erlang is good !"). Child: <0.45.0> got: "Erlang is good !" Child: <0.44.0> got: "Erlang is good !" Child: <0.43.0> got: "Erlang is good !" Child: <0.42.0> got: "Erlang is good !" Child: <0.41.0> got: "Erlang is good !" Child: <0.39.0> got: "Erlang is good !" ok 6> generator:send_to_kids("1+1 = 2"). Child: <0.45.0> got: "1+1 = 2" Child: <0.44.0> got: "1+1 = 2" Child: <0.43.0> got: "1+1 = 2" Child: <0.42.0> got: "1+1 = 2" Child: <0.41.0> got: "1+1 = 2" Child: <0.39.0> got: "1+1 = 2" ok 7>A process registered as
generatoris started and may be told to start any number of children processes. The child process is generically created from the{M, F, A}combination sent to thegenerator. The generator loop keeps a track record of the processes created. It can then be told to broadcast messages to all processes.However, in practice/ production, you might not to do this, because the
generatorloop may consume lots of memory as the listBuffergrows since thats where we keep all thePidsof our processes. You can also useETS Tables, orMnesiae.t.c but i havenot used them in the example because they will seem a little bit more advanced. Look at this question and its answer to understand more.