Here is my code:
-module(cooperate).
-compile(export_all).
producer(_Pid, 0) ->
done;
producer(Pid, N) ->
io:format("process ~p producing ~p~n", [Pid, rand:uniform(N)]),
producer(Pid, N-1).
start() ->
spawn(cooperate, producer, [rand:uniform(7), 7]).
Results:
{ok,cooperate}
2> cooperate:start().
process 2 producing 6
<0.88.0>
process 2 producing 3
process 2 producing 4
process 2 producing 4
process 2 producing 1
process 2 producing 2
process 2 producing 1
3>
Expecting:
process <0.88.0> producing 6
process <0.88.0> producing 3
process <0.88.0> producing 4
process <0.88.0> producing 4
process <0.88.0> producing 1
process <0.88.0> producing 2
process <0.88.0> producing 1
What should I do if I want to print <0.88.0> between process and producing instead of 2? I tried something like pid_to_list, ~p, etc
The first argument of your producer function is named Pid, yet you never pass any pid as the first argument of this function. The argumenr when the function is first called is rand:uniform(7), which in your test happen to return 2.
If you want your function to print the pid of the process you spawned, the best way would be to get rid of the first argument, and use self() instead.