0

I want to assign value to att = 5 in thread t. In the main thread, I want to check if att has been assigned to 5 yet

When I run the void check(), the output is always 3. Why is this?

class Program
{
    static int att = 3;
    static void Main(string[] args)
    {
        Thread t = new Thread(() => set(att));
        t.Start();
        check();
    }
    static void set(int para)
    {
        para = 5;
    }
    static void check()
    {
        while (att != 5)
        {
            Console.WriteLine(att);
        }
        Console.WriteLine(att);
    }
}
Sam
  • 4,475
  • 2
  • 28
  • 31
Fish
  • 165
  • 3
  • 16

2 Answers2

0

You are editing the para variable rather than the att variable so att will always equal 3.

Try changing this:

static void set(int para)
{
    para = 5;
}

To:

static void set(int para)
{
    att = 5;
}
Loocid
  • 6,112
  • 1
  • 24
  • 42
  • what if I have an array of att `int[] att = new int[10];` and I want to change the value of each `att[i]` in different thread `t[0], t[1] . . . t[9]`, and each thread receive method `set` – Fish Jul 22 '15 at 03:12
  • @Fish I cant answer that in a comment easily. – Loocid Jul 22 '15 at 03:17
  • Okey, I've found the solution :) Thanks anyway – Fish Jul 22 '15 at 03:28
0

Changing the value of para in your set() method won't have any effect on the original value of att, unless you specify that the parameter should be passed by reference.

Also, you'll want to call Join() on your thread to make sure it doesn't try printing the value to the console before the thread has actually finished modifying it.

static void Main(string[] args)
{
    Thread t = new Thread(() => set(ref att));
    t.Start();
    t.Join();

    check();
}

static void set(ref int para)
{
    para = 5;
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165