Reputation: 99
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?
Upvotes: 0
Views: 212
Reputation: 117084
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
.
Upvotes: 2
Reputation: 34
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.
Upvotes: 0