Blocking Vs Non Blocking |
We had presented some introductory tutorial on blocking and non blocking assignment. We will now present some real life issues, solution and best practices for blocking and non blocking assignment statements
Consider the 4 bit ring counter example. A 4 bit ring counter will count as
0001
0010
0100
1000
0001
..
.
and so on
The following is one implemmentation of the 4 bit ring counter
// referencedesigner.com // 4 bit ring counter example module four_bit_ring_counter ( input clock, input reset, output [3:0] q ); reg[3:0] a; always @(posedge clock) if (reset) a = 4'b0001; else begin a <= a<<1; // Notice the non blocking assignment a[0] <=a[3]; end assign q = a; endmodule |
At the reset, the initial value of the counter is 4'b1000. The ring counter is basically an implemmentation of left shift except when the MSB is 1. When the MSB is 1, its value is copied to the LSB.
A following test bench is used to display the values
`timescale 1ns / 1ps module stimulus; // Inputs reg clock; reg reset; // Outputs wire[3:0] q; // Instantiate the Unit Under Test (UUT) four_bit_ring_counter r1 ( .clock(clock), .reset(reset), .q(q) ); always #10 clock = ~clock; initial begin // Initialize Inputs clock = 0; reset = 0; #5 reset = 1; #20 reset = 0; #100 $finish; end initial begin $monitor($time, " clock=%1b,reset=%1b,q=%4b",clock,reset,q); end endmodule |
It will give the following output
0 clock=0,reset=0,q=xxxx
5 clock=0,reset=1,q=xxxx
10 clock=1,reset=1,q=0001
20 clock=0,reset=1,q=0001
25 clock=0,reset=0,q=0001
30 clock=1,reset=0,q=0010
40 clock=0,reset=0,q=0010
50 clock=1,reset=0,q=0100
60 clock=0,reset=0,q=0100
70 clock=1,reset=0,q=1000
80 clock=0,reset=0,q=1000
90 clock=1,reset=0,q=0001
100 clock=0,reset=0,q=0001
110 clock=1,reset=0,q=0010
120 clock=0,reset=0,q=0010
The most important line to see is
a <= a<<1; // Notice the non blocking assignment
a[0] <=a[3];
For example consider the case when the a has the value 1000. Usind the non blocking statement a <= a<<1, it is shifted towards left by 1. But before this execution blocks the execution of the next statement
a[0] <=a[3];
we want to assign [a3]'s value to a[0].
If we write the blocking statements in place of non blocking as in
a = a<<1;
a[0] =a[3];
The output as given by icarus compiler was
0 clock=0,reset=0,q=xxxx
5 clock=0,reset=1,q=xxxx
10 clock=1,reset=1,q=0001
20 clock=0,reset=1,q=0001
25 clock=0,reset=0,q=0001
30 clock=1,reset=0,q=0010
40 clock=0,reset=0,q=0010
50 clock=1,reset=0,q=0100
60 clock=0,reset=0,q=0100
70 clock=1,reset=0,q=1001
80 clock=0,reset=0,q=1001
90 clock=1,reset=0,q=0010
100 clock=0,reset=0,q=0010
110 clock=1,reset=0,q=0100
120 clock=0,reset=0,q=0100
In the blocking case, the two statements execute sequantially. And therefore, when a is 0100 , and the first blocking assignment a = a << 1; makses is 1000. The next assignment statement a[0] =a[3]; executes next SEQUENTIALLY and a[0] gets assigned as 1. Hence the unexpected result of 1001.