0

As far as I know, the variable in thread should be not safe if not locked. But I tried it on Unity, and found it different. I try the code below:

    void Awake () {
        Thread thread = new Thread(new ThreadStart (demo));
        thread.Start ();
        for (int i = 0; i < 5000; i++) {
            count = count + 1;
        }
    }

    void demo() {
        for (int i = 0; i < 5000; i++) {
            count = count + 1;
        }
    }

And I try to Debug.Log(count), and every times I try it that is 10000. But it should be a number which is less than 10000 because of not thread safety, shouldn't it? So can anyone tell me why?

3
  • Can you please post a minimal reproducible example so that we can copy-paste-and-run your code? Commented Feb 22, 2017 at 2:16
  • can you show us the code where you invoke the awake method Commented Feb 22, 2017 at 2:16
  • @OusmaneDiaw - We need the full code, not just the call to .Awake(). We need a minimal reproducible example. Commented Feb 22, 2017 at 2:19

2 Answers 2

2

Here's an Minimal, Complete, and Verifiable example of your code:

void Main()
{
    Awake();
    Console.WriteLine(count);
}

private int count = 0;

public void Awake()
{
    Thread thread = new Thread(new ThreadStart(demo));
    thread.Start();
    for (int i = 0; i < 5000; i++)
    {
        count = count + 1;
    }
    thread.Join();
}

public void demo()
{
    for (int i = 0; i < 5000; i++)
    {
        count = count + 1;
    }
}

If you run that you get 10000 out. This is because by the time the thread has started the .Awake() method has finished its loop and thus no conflict occurs.

Try changing the loops to for (int i = 0; i < 50000; i++) then the result I got for one run is 89922. It changes each time, but sometimes I still get 100000.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply, that helps me a lot.
0

The thread need some time to schedule to start. The main thread might finish the increments before the other thread start. Try to use a large value like 50000000.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.