-5
static void Main(string[] args)
{
    int i = 10;

    Program th = new Program();

    Thread t2 = new Thread(() => thread2(out i));
    t2.Start();
    Thread t1 = new Thread(() => thread1(i));
    t1.Start();
    Thread.Sleep(5000);

    Console.WriteLine("Main thread exits." + i);
    Console.ReadLine();
}

static void thread1(int i)
{
    Console.WriteLine(i);
    i = 100;
}

static void thread2(out int i) // what should be the value of i???
{
    Thread.Sleep(5000);
    i = 21;           
    Console.WriteLine(i);
}

what should be the value received in called method while we are passing out parameters?? "whether it is zero or the value we are passing"

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215

1 Answers1

0

based on your code

static void Main(string[] args)
{
    int i = 10;

    Program th = new Program();

    Thread t2 = new Thread(() => thread2(out i));
    t2.Start();
    Thread t1 = new Thread(() => thread1(i));
    t1.Start();
    Thread.Sleep(5000);

    Console.WriteLine("Main thread exits." + i);
    Console.ReadLine();
}

First function thread2 will receive value i = 10 . but

in Second function you will either receive i =10 or i =21 , because its all depends on execution done at CLR/CPU level.

what I mean to say here is if you thread2() method execution get finished before it reaches to execution of thread1() then thread1() will receive 21. But if excution not get finished then receive 10 as input.

above is true if you remvoe this line Thread.Sleep(5000); from your thread2() function.

But if you dont than 10 will get passed to both function and main thread print 10 in ideal scenario , but this also depends on context switching ...your ouput is not fixed here. it all on processing and execution.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263