Why loop variable should not be used in FORK JOIN_NONE

In reply to Yash_wanth12345:

First of all, there is no need for the automatic keyword in any of this code as class methods can only have automatic lifetimes, and all the variables declared within a class method have automatic lifetimes by default.

The key to answering your question is understanding when an automatic variable gets created and initialized, and when statements inside fork/join_none get executed.

In the first snippet, the initial block calls main_task, which forks two calls to sub_task. Inside the sub_task, there is a for loop that creates a loop iterator variable i. Since main_task gets called 4 times, that means 8 calls to sub_task and that creates 8 instances of the loop iterator variable i There is a fork_join/none inside the for loop having a begin/end that references i, so the lifetime of i gets extended until that begin/end block finishes, and by then all 8 loop iterators have the value 3.

A fork/join_none does not start executing any of its nested blocks or statements until the parent thread suspends or terminates. Since the inner for loop iterates 3 times, there are a total 24 begin/end blocks queued to start executing when the parent initial thread terminates. At that point, all 8 instances of the iterator variable i have reached their final value 3.

In the second snippet you have declared ch inside the inner for loop, so that means there will be 24 instances of that variable, each with their lifetime beginning at iteration of the for loop initialized with the current value of i.

Note that you have a typo with the declaration of ch. you have it outside the for-begin block; it should be inside. It also makes no difference if you put the declaration of ch inside the fork-begin. In both cases there we be 24 instances of that variable, each with their lifetime beginning at iteration of the for loop initialized with the current value of i.