semaphore

Semaphore is a used when multiple process want to use a shared resource like a shared variable.

  • Conceptually, a semaphore is a bucket
  • Semaphores are typically used for mutual exclusion, access control to shared resources, and for basic synchronization
  • When a semaphore is allocated, a bucket that contains a fixed number of keys is created
  • Processes using semaphores must first procure a key from the bucket before they can continue to execute
  • If a specific process requires a key, only a fixed number of occurrences of that process can be in progress simultaneously
  • Semaphore is a built-in class that provides the following methods:

     Create a semaphore with a specified number of keys: new()
     Obtain one or more keys from the bucket: get()
     Return one or more keys into the bucket: put()
     Try to obtain one or more keys without blocking: try_get()

  • Semaphores can be used in a testbench when you have a resource, such as a bus, that may have multiple requestors from inside the testbench but as a part of a physical design, can only have one drive

    Method new()

    new() function is a semaphore object constructor. It specifies the number of keys initially allocated to the semaphore. The default value of the keys is zero.
    Syntax:
    function new(int keyCount = 0 );
    The new() function returns the semaphore handle or, if the semaphore cannot be created, null.

    Method get(

    get() method is used to get a specified number of keys from a semaphore.
    Syntax:
    task get(int keyCount = 1);
    The keyCount specifies the required number of keys to obtain from the semaphore. The default is 1. If the specified number of keys is available, the method returns and execution continues. If the specified number of keys is not available, the process blocks until the keys become available. The semaphore waiting queue is first-in first-out (FIFO). This does not guarantee the order in which processes arrive at the queue, only that their arrival order shall be preserved by the semaphore.

    Method put()

    put() method is used to return keys to a semaphore.
    Syntax:
    task put(int keyCount = 1);
    The keyCount specifies the number of keys being returned to the semaphore. The default is 1. When the semaphore.put() task is called, the specified number of keys is returned to the semaphore. If a process has been suspended waiting for a key, that process shall execute if enough keys have been returned.

    Method try_get()

    try_get() method is gets a specified number of keys from a semaphore, but without blocking.
    Syntax:
    function int try_get(int keyCount = 1);
    The keyCount specifies the required number of keys to obtain from the semaphore. The default is 1. If the specified number of keys is available, the method returns a positive integer and execution continues. If the specified number of keys is not available, the method returns 0.