Friday, August 20, 2010

fork…join_none and for loop

An interesting case with fork…join_none block defined inside a for loop in system verilog is shown here as an example:

image

 

The intended result of this code is to display the iteration count value, i, from 0 to 3. That is, each call to system task, $display, will hold a unique value of i.

But the output of the above example is:

image

This can be explained as: Each iteration in the for loop initiates a parallel thread to display the value of variable i (iteration count). Because of join_none keyword, none of the threads (blocks) are waited for completion of their execution. So the immediately next statement after the for loop (zero time delay) is executed, which in this case is $display (“THE END”) system task and hence is the first line of output observed.

By the end of execution of for loop (zero time), the value of i is 4. This is the value that gets updated across all the threads (blocks) that has been initiated to display the value of i. Even before the threads begin to start executing the value of i has been changed to 4, which is what is observed in the output. This result implies that variable i is a static variable.

For this particular example replacing join_none by join statement will result into the expected output. That is, each parallel thread will display unique value of i and the output seen is i changing in consecutive order from 0 to 3.

In case join_none statement cannot be replaced because, say for example, of time consuming user defined task being called and the logic requires that no time is to be spent before executing the next statement following the for loop, then create an automatic variable inside a for loop and assign i to it before starting the fork…join_none block.

image

Here, keyword automatic can be ignored as well. Variable k is roughly similar to C automatic variable. Now, the lifetime of automatic variable k is the lifetime of each fork...join_none block. So each block will have a unique value of k, which doesn’t get changed even after completion of for loop. 

image

1 comment:

suraj said...

Why number in reverse order...


Powered By Blogger