Do you see nay issue in above code? is yes, whats the issue you see?
i am able to start 5 thread and once 3 thread finished , kill the other 2 thread with above code.
There is no problem with the code shown above because each task finishes at a unique time. But you have race conditions if multiple tasks finish in the same region of a time step. Suppose you change task t4 to have a delay of #15. Then both t2 and t4 finish concurrently. It’s possible for
count to skip from 2 to 4 and
wait(count==3) never sees the expression being true.
Another problem is the ++ operator is a non-atomic read-modify-write operation that could be written as
count = count + 1;. This is always a problem when you have multiple threads accessing the same global variable.
The best way of handling this is using a semaphore. Each thread does a
sema.put(1), and replace the
wait with
sema.get(3);.
Inside fork and join_none we have multiple tasks which are generally time consuming events so in that case semaphores are helpful. But in the above program if we use functions or tasks (without any delays) calls then semaphores are not helpful. Since they will executed within zero time it is not possible to handle such threads once when we call them.
But in actual software, don’t we run threads interleaved and not parallel? So only one process should increment the count variable at a time. We should be able to see count == 3.
Using a semaphore implies potentially blocking threads. That is as good as time-consuming to solve the problem. In reply to ledzep_1988:
Let’s say count is 2, and there are two processes scheduled to increment count at the same time. The first process increments count from 2 to 3. That schedules the process waiting for a change on count to wake up and evaluate its wait expression. SystemVerilog does not guarantee the order of process evaluation so it’s possible that the other process increments count to 4 before wait expression gets evaluated.
Using semaphore also
Suppose we change task t4 to have a delay of #15. Then both t2 and t4 finish concurrently. four thread gets completed instead of 3 expression being true.
Is this is expected.
Please correct me if I am wrong.