Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread and Task scheduling

I have a code which synchronize threads via AutoResetEvent

Basically there are two threads which swap control and execute commands , each thread at a time.

Code :

static EventWaitHandle _waitHandle = new AutoResetEvent(false);
static void Waiter()
{

    _waitHandle.WaitOne();
    Console.WriteLine("A...");
    _waitHandle.Set();  
    _waitHandle.WaitOne();
    Console.WriteLine("A2...");
    _waitHandle.Set();
}

static void Waiter2()
{   
    _waitHandle.WaitOne();
    Console.WriteLine("B...");
    _waitHandle.Set();
    _waitHandle.WaitOne();
    Console.WriteLine("B2...");
}


void Main()
{
    new Thread(Waiter).Start();
    new Thread(Waiter2).Start();
   _waitHandle.Set(); // Wake up the Waiter.
}

Result : (I always get this result)

A...
B...
A2...
B2...

However - when I move to Tasks :

Task.Run(()=>Waiter());
Task.Run(()=>Waiter2());

I sometimes get :

B...
A...
B2...

Which is clear to me because the task scheduler scheduled the second task to execute first.

Which leads me to ask :

Questions

1) Do threads order guaranteed to be the same as order of invocation in :

new Thread(Waiter).Start();
new Thread(Waiter2).Start();
//In other words , will I always get the first result ?

2) How can I Force the Task.Runs to be invoked the same order as I invoke them?

like image 601
Royi Namir Avatar asked Jun 20 '26 10:06

Royi Namir


1 Answers

  1. No, it is not guaranteed, you just got lucky that the output was the same every time.
  2. Add in a 2nd AutoResetEvent that has a WaitOne between the two tasks and a Set in at the start of the Waiter method.
like image 195
Scott Chamberlain Avatar answered Jun 22 '26 00:06

Scott Chamberlain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!