Skip navigation.
Home

System Verilog Mailbox with try_get

A mailbox in SystemVerilog is a very useful method of inter-process communication. Sometimes it is desired to read data from a mailbox from a process without blocking the process. This can be accomplished with the try_get() function as this snippet demonstrates. try_get() will return 0 if there is no data in the mailbox and 1 if there is data in the mailbox. It may also return -1 if there is an error condition.

program mailbox_test();
 
class Transmitter;   // Transmitter sends values 0-19
mailbox #(byte) mb;
 
  function new(mailbox #(byte) mb);
    this.mb = mb;
  endfunction
 
  task run;
    for(byte ii=0;ii<20;ii++) mb.put(ii);
  endtask
endclass
 
class Receiver;  // Receiver gets values from transmitter and displays them.
mailbox #(byte) mb;
byte      rx_val;
 
  function new(mailbox #(byte) mb);
    this.mb = mb;
  endfunction
 
  task run;
     int flag;
     while (1) begin
        flag = mb.try_get(rx_val);
        if (flag == 1) 
          $display("rx val = %d",rx_val);
        #10;
     end
  endtask
endclass
 
mailbox #(byte) mb;        // maibox used for communcation.
Transmitter t1;    // Transmitter.
Receiver r1;       // Receiver.
 
initial begin
  mb = new;        // Create new objects.
  t1 = new(mb);
  r1 = new(mb);
  fork             // Fork off the processes.
    t1.run();
    r1.run();
  join
end
endprogram
 
module tb_mailbox;  // kick off the test.
mailbox_test test();
endmodule