How to wait for how fork-join_none threads spawned from a loop?

I am using “wait fork” to wait for multiple fork-join_none threads spawned from a for loop. But the “wait fork” is not waiting for spawned threads to finish.
Here’s a sample code:


 1       fork
 2           for (int i = 0; i < 3; i++)
 3           begin
 4               fork
 5                   automatic int job_id = i;
 6                   begin
 7                       $display("Job[%0d] Started @ %0t", job_id, $time);
 8                       #5us;
 9                       $display("Job[%0d] Finished @ %0t", job_id, $time);
 10                  end
 11              join_none
 12          end
 13          wait fork;
 14          $display("Forked Jobs Finished at %0t", $time);
 15      join
 16      #10us;

When I run the above code, I get following results. I would like to wait for all forked jobs to finish before line # 14 is executed (i.e. at 5us). How do I wait for forked threads in the loop?

Job[2] Started @ 0

Job[1] Started @ 0

Job[0] Started @ 0

Forked Jobs Finished at 0

Job[2] Finished @ 5000

Job[1] Finished @ 5000

Job[0] Finished @ 5000

Thanks
-Kal

In reply to KalP:

Your problem is you are using an outer fork/join block instead of begin/end. So the for-loop, wait fork, and $display statements execute in parallel instead of in sequence.

In reply to dave_59:

That worked… Thanks for the quick response.

Or u can use delay to the display at the end

fork
            for (int i = 0; i < 3; i++)
            begin
                fork
                   automatic int job_id = i;
                    begin
                        $display("Job[%0d] Started @ %0t", job_id, $time);
                        #5us;
                        $display("Job[%0d] Finished @ %0t", job_id, $time);
                   end
               join_none
           end
           wait fork;
          #5us $display("Forked Jobs Finished at %0t", $time);
     join
      #10us;