Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get fork join/join_any to work with a loop

As per the SV LRM section 9.3.2

for(int j=1; j <=3; ++j)
fork
    automatic int k = j;
    begin
        .... # use k here
    end
join_none

this is how to create a fork in a loop. I have tried it and it works. But if i want to create fork with join and not join_none in loop it does not work as expected but works sequentially.

How can i modify this to work using a join, i want all my forks to fork off simultaneously and then wait for all of them to finish(join) or one of them to finish(join_any)?

Thanks

like image 321
justrajdeep Avatar asked Dec 10 '25 19:12

justrajdeep


1 Answers

If you want to wait for all of the processes fork'ed by the fork-jone_none to complete, you put a wait fork; statement after the for loop. The wait fork statements waits for all child processes of the current thread to complete.

Id there are processes created by fork-jone_none before this for loop still active that you do not want to wait for, you need to put this piece of of code in an isolation thread.

fork
  some_other_process;
join_none
fork 
  begin : isolation_process
    for(int j=1; j <=3; ++j) begin : for_loop
      fork
         automatic int k = j;
         begin
            .... # use k here
         end
      join_none
    end : for_loop
  wait fork; // will not wait for some other process
 end :isolation_thread
 join

To get the behavior of the fork-join_any requires some handshaking signal or event in each process to signal that it is done.

event join_any_event;
for(int j=1; j <=3; ++j) begin : for_loop
      fork
         automatic int k = j;
         begin
            .... # use k here
            ->> join_any_event;
         end
      join_none
    end : for_loop
  @join_any_event;
like image 141
dave_59 Avatar answered Dec 12 '25 18:12

dave_59



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!