Producer consumer interaction


mailbox mbx=new();
class packet;
  static int id;
  function new;
    id++;
  endfunction: new
endclass: packet

class producer;
  packet h_pkt;
  task produce();
    for(int i=0;i<5;i++)begin
      #5;
      h_pkt=new();
      $display("packet %0d is produced at time %0t",i+1,$time);
      mbx.put(h_pkt);
    end
  endtask: produce
endclass: producer

class consumer;
  packet h_pkt[5];
  task consume();
    for(int i=0;i<5;i++)begin
      #16;
      mbx.get(h_pkt[i]);
      $display("packet %0d consumed at time %0t",h_pkt[i].id,$time);
    end
  endtask: consume
endclass: consumer

module tb_top();
  producer p;
  consumer c;
  initial begin
    p=new();
    c=new();
    fork
      p.produce();
      c.consume();
    join
  end
endmodule: tb_top

output:

packet 1 is produced at time 5

packet 2 is produced at time 10

packet 3 is produced at time 15

packet 3 consumed at time 16

packet 4 is produced at time 20

packet 5 is produced at time 25

packet 5 consumed at time 32

packet 5 consumed at time 48

packet 5 consumed at time 64

packet 5 consumed at time 80

why when I try to get a value from the mailbox I can’t?
producer thread i working as expected so does the consumer thread. But why all the packet’s aren’t consumed and how 5th packet get consumed again and again even when I pulled it from the mailbox?

In reply to Thobiyas:

By using a static variable, all instances of packet will have the same ‘id’. Hence, every time you new() the object, all ‘packets’ will have their ‘id’ incremented.

In reply to Thobiyas:
What you probably want is

class packet;
  static int counter;
  int id;
  function new;
    id = counter++;
  endfunction: new
endclass: packet
mailbox #(packer) mbx=new();


Also suggest that you use parameterized mailboxes. You’ll get better error messages at compile time rather than trying to debug mistakes at runtime.