- Home /
Threads don't operate properly in every frame.
Edit: OK. It's just my mistake for not reset the variable.
I've tried to implement the multithreading. I'm still not familiar with it. This is the code. There is no error or warning so I think the code is fine.
private int _threadCounter = 0; private float[] _num; private Vector3 _vec01, _vec02;
IEnumerator Start () { Thread[] thread = new Thread[2]; _num = new float[threads];
_vec01 = 22 * new Vector3(1, 0, 0);
_vec02 = 33 * new Vector3(1, 0, 0);
while (true)
{
for (int i = 0; i < threads; i++)
{
thread[i] = new Thread(TestMethod);
thread[i].Start(i);
}
while (_threadCounter < 2) yield return null;
print(_num[0] + " " + _num[1]);
yield return null;
}
}
private void TestMethod(object iteration) { int iter = (int)iteration;
_num[iter] = iter + 10;
Add100(ref _num[iter]);
_num[iter] += Return1000();
if (iter == 0)
_num[iter] *= _vec01.magnitude;
else _num[iter] *= _vec02.magnitude;
_threadCounter++;
}
private void Add100(ref float iter) { iter += 100; }
private int Return1000() { return 1000; }
I just want to play with return variable and some simple calculation. So the method may look non-sense. Please don't care about it. :) I've monitored the array variable _num in every frame. The system should print 24420 36663. The problem is that sometimes the second thread didn't calculate the entire method. The system printed 24420 1111 (or 111) which means it didn't do all calculation. It didn't happen often though. It might be just a fraction of seconds. But it did happen more often if I increased the magnitude of multiply vector. What did I do wrong here? What was the caused of this problem?
Answer by Mike 3 · Jul 14, 2010 at 02:18 AM
It's doing the calculation just fine - remember that it's threaded, it's often going to be half way through the function when you're checking the current results
If the issue is that your code should be waiting for both threads to finish before posting the results, then you'll need to reset the threadCounter variable to 0 at the top of your while loop, otherwise it'll skip it after the first iteration
One thing I'll add though - you should probably look into how to design threadsafe code, having two threads accessing the same data can be catastrophic later
Arg! How could I forget to reset threadCounter variable. >_<
Big thanks to you!