Fork join_none inside for loop

In reply to ssubramaniam1990@gmail.com:
The differences are in the lifetime of the variable index, and the timing of when that variable gets assigned with value of the variable i.

Realize that there will be 16 concurent variables named index and only one named i. In case 1) & 2), the index variable gets created upon each entry into the fork/join_none block. That occurs before spawning any process within the fork/join_none. In case 1) the variable initialization also occurs before any process within the fork/join_none. The thing that you need to remember is that automatic variables get created upon entry and initialized before executing any procedural statement within the block they are located in. So in case 1), each index variable gets the current value of i in each loop iteration.

In case 2), you moved the initialization into a separate procedural assignment statement. Each statement within a fork/join_none becomes as new child process and execution of the child process does not begin until the current parent thread suspends. The for loop now spawn 32 threads before suspending at the wait forkstatement when the value of i is 16. (and as I said before, it is a race if send(index) sees the unitialized value 0 or assigned value 16.

In case 3), the index variable is now declared inside a begin/end block, which is a single statement for the fork/join_none. So now the index variable does not get created until all 16 processes have been spawned, and the value of i is 16.

1 Like