How to control the flow when multiple threads are running

Hi Everyone,
I’m facing an issue with my code
Following is the piece of code

for(int i=0; i<10; i++) 
  fork
     int j = i; 
     schedule_data_on_if(j);
  join_none

task schedule_data_on_if(input int index) ;
  forever begin
    wait(q_in[index] !=0);                           // Input queue
    $display(“Before delay in thread %0d”, index);   // All these prints are happening in order
    repeat(50) @(posedge clk);                       // DELAY 
    $display(“After delay in thread %0d”, index);    // How to control this statement execution ??
  end
endtask

Input Description:
I have an array of input queue(q_in). From my sequence I will fill this queue with indexes 2 7 4 in order (at 0 time)

Output Expected
Before delay in thread 2
Before delay in thread 7
Before delay in thread 4
After delay in thread 2 // (PROBLEM STARTS HERE)
After delay in thread 7
After delay in thread 4

Output Coming:
Before delay in thread 2
Before delay in thread 7
Before delay in thread 4
After delay in thread 4 // WHY IS IT HAPPENING EXACTLY OPPOSITE ??
After delay in thread 7
After delay in thread 2

Question:
Here 10 threads are running parallel and the statements before the delay (repeat stat) are executing in the same order, the way I’ve given input.
Why are the statements executed after the delay statement are happening exactly opposite.

Requirement
My requirement is to control the execution of statement after the delay, in the same order, the way I’ve given the input at 0 time. How can this be done?

P.S: Please do ignore the typos and syntaxes

You can’t control, nor should you depend on the order of parallel threads synchronized to the same event (@posedge clk). You don’t show how q_in[index] gets modified, but if they are all at time 0, there’s also no guarantee about the ordering before the delay either.

If you require a particular execution ordering, then you should not be using parallel threads, or you need to use a semaphore/mailbox that guarantees FIFO thread ordering. I would need to know more about what you are trying to accomplish and the reasoning behind your requirements to suggest an alternative.

In reply to dave_59:

Hi Dave,

Thanks for the response.

Actually I’m trying to develop a MODEL, where it should have capability of driving 256 address locations(in our code index)

Always frames/packets from same destination addr must be sent with some GAP/delay. This gap/delay varies from one dest. addr(DA) to other. So, I’m trying to activate the queues of all DAs, at 0 time, and will control the delay from the time user puts the data from sequence.

The user of the MODEL when gives the input frames in particular order to MODEL, they expect them to go in same order on interface, and we have given a provision where user can give all the Inputs at 0 time

FYI: The code which I have posted is the very much simplified version of what actually I’m doing

Regards,
Santosh Kumar Vangala