Start a Thread in Class Constructor
I created an example class to demonstrate what I'm trying to do. Each class should run its calculation on a separate thread.
using System.Collections;
using System.Threading;
public class PlayAShoe {
private static readonly System.Random random = new System.Random();
private static readonly object synlock = new object();
private int rnum = 0;
public int currthread;
public bool isFinished;
public PlayAShoe(int i)
{
isFinished = false;
currthread = i;
System.Threading.ParameterizedThreadStart pts = new System.Threading.ParameterizedThreadStart(startShoe);
System.Threading.Thread waitforone = new System.Threading.Thread (pts);
waitforone.Start (i);
//startShoe();
}
public int getNum()
{
return rnum;
}
private void startShoe(object threadparams)
{
for (int i = 0; i < 5000000; i++)
{
rnum += RandomNumber(0, 10);
}
isFinished = true;
}
public static int RandomNumber(int min, int max)
{
lock (synlock)
{
return random.Next(min, max);
}
}
}
In my controller script I make 4 of these classes. And print the result in the update function once they are finished:
public class SimulationController : MonoBehaviour {
PlayAShoe newshoe1;
PlayAShoe newshoe2;
PlayAShoe newshoe3;
PlayAShoe newshoe4;
void Start ()
{
newshoe1 = new PlayAShoe(1);
newshoe2 = new PlayAShoe(2);
newshoe3 = new PlayAShoe(3);
newshoe4 = new PlayAShoe(4);
}
void Update ()
{
if (newshoe1.isFinished)
{
print(newshoe1.getNum() + " " + newshoe1.currthread);
newshoe1.isFinished = false;
}
if (newshoe2.isFinished)
{
print(newshoe2.getNum() + " " + newshoe2.currthread);
newshoe2.isFinished = false;
}
if (newshoe3.isFinished)
{
print(newshoe3.getNum() + " " + newshoe3.currthread);
newshoe3.isFinished = false;
}
if (newshoe4.isFinished)
{
print(newshoe4.getNum() + " " + newshoe4.currthread);
newshoe4.isFinished = false;
}
}
}
I understand how to do this without using a separate class but eventually the calculation done in PlayAShoe will have many lists and variables used in the long calculation making a class the most useful way to do it. The problem is I need to make it faster so I thought I could split this up by making several classes run the long calculation on separate threads and just grab the results when they're done. The problem is it is actually much faster when I don't create the thread in the constructor and just do a function call instead. Why is this?