Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In your lists:foreach call in the second block, you are calling <code>RESULT=prime:is_prime(ProcId,N)</code>, which is doing a <code>receive</code> for the result. So, you're spawning a process and then waiting for it to finish until you spawn the next process. That's why it takes the same amount of time as the single-threaded approach: both ways, you're only doing one at a time.</p> <p>Instead, you need to spawn all the processes first (using something like <code>lists:map</code> to keep track of all the PIDs) and then wait for the results in a separate step. Note that means you'll have to split the <code>ProcessID ! {self(),Number}</code> part from the <code>receive</code> part so that can be done in the first step, otherwise you're just spawning a bunch of idle processes.</p> <p>So, something like:</p> <pre><code>Pids = lists:map( fun(N)-&gt; ProcId = prime:start(N), io:fwrite("Calculating : procId=~p N=~p ~n",[ProcId,N]), ProcId end, NUMS). lists:foreach( fun(ProcId) -&gt; {N,RESULT}=prime:is_prime(ProcId), io:fwrite("Result procId=~p N=~p Result=~p ~n", [ProcId,N,RESULT]) end, Pids). start(N)-&gt;spawn(?MODULE, forever_function, [N]). forever_function(Number)-&gt; Result = is_prime(self(),2,Number), receive { From, get_result } -&gt; From! {Number,Result}, % unnecessary since we never call this Pid again, but do it anyway :) forever_function() % could also add more cases here to set the number % or even do a one-shot function like before end. %multithreaded function is_prime(ProcessID)-&gt; ProcessID ! {self(),get_result}, receive RESULT-&gt;RESULT end. </code></pre> <p>Note: this is untested, so it may need some tweaking.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload