A function is meant to do some processing on the input and return a single value. In contrast, a task is more general and can calculate multiple result values and return them using output and inout type arguments.
Tasks can contain time-consuming simulation elements such as @, posedge, and others. Tasks are used in all programming languages, generally known as procedures or subroutines.
Data is passed to the task, the processing is done, and the result returned. They have to be specifically called, with the data ins and outs, rather than just wired into the general netlist.
Included in the main body of code, they can be called many times, reducing code repetition.
A task must be specifically called with a statement. It cannot be used within an expression as a function can.
A task begins with keyword task and ends with keyword endtask. Inputs and outputs are declared after the keyword task.
Local variables are declared after input and output declaration.
The keyword automatic will make the reentrant task. Otherwise, it will be static by default. If a task is static, all its member variables will be shared across different invocations of the same task that has been launched concurrently.
NOTE: Hierarchical references cannot access an automatic task item.
Calling a task
If the task does not need any arguments, then a list of arguments can be avoided. If the task needs arguments, they can be provided in the same statement as its invocation.
The task-enabling arguments (x, y, z) correspond to the arguments (a, b, c) defined by the task.
Since a and b are inputs, values of x and y will be placed in a and b, respectively. Because c is declared output and connected with z during invocation, the sum will automatically be passed to the variable z from c.
Tasks that are declared outside all modules are called global tasks as they have a global scope and can be called within any module.
After executes the above code, it produces the following output.
Difference between Function and Task