How to mutex the task

I have a snippet of code shown below.


fork
  A(1);
  A(2);
  A(3);
join

and the task A is like below.


task A(int i);
case (i)
  1 : begin
      B(…);
  end
  2 : begin
      B(…);
  end
  3: begin
     B(…);
  end
...
...
endtask : A

And here the task B is a little special because I want it to be an atomic operation, which means only one time to call at the same cycle. Namely when the task B is called by one thread, other threads must wait, until the thread invoking task B is completed. How can I make it happened ?

In reply to zz8318:
This is exactly the purpose of semaphores

task automatic B; // if this is a class method, it is already automatic
  static semaphore s = new(1);
  while (!s.try_get) @(posedge clk);
  // mutex body of B
  #0 s.put();
endtask

The #0 is needed to meet your requirement that only B task execute per cycle. I normally don’t like using #0’s because of their tendency to accumulate, but that won’t happen here if get() is synchronous to a clock edge.

In reply to dave_59:

Thanks Dave. It works.

what I tried before is below. but it didn’t work. could you please give me a hint why not worked ? (I have a bit variable named mutex in this class)


bit mutex = 1;



task A(int i);

wait(mutex);
mutex = 0;

case (i)
  1 : begin
      B(…);
  end
  2 : begin
      B(…);
  end
  3: begin
     B(…);
  end
...
...

mutex = 1;

endtask : A


In reply to zz8318:

It would certainly help to describe in more detail what “didn’t work” means. What were you expecting to see and what actually happened?

I’m going to assume that you saw all 3 calls to A proceeded without waiting. That is because statements within a process are not “atomic” between concurrent processes. That means it’s. possible for one process can test the value of mutex and another process can also test before the next statement sets the mutex value back to 0. Only a semaphore and mailbox give you an atomic test and set as a single operation.

In reply to dave_59:

great. I get it. Thank you for your great help !