Hi, running in editor mode, I have 9 threads that process different sections of 2D terrain data. I all works fine but it’s a pain to create 9 different but identical copies of a function for each thread.
What I want to do is:-
for (int i = 0; i < 9; i++)
{
myThreads = new Thread(new ThreadStart( () => DoHeightmap( i )));
myThreads*.Start();*
}
Where the thread is started with the parameter ‘i’ which is the section each thread should process.
This only works sometimes, as I get the odd corrupted sections every time I run the threads. I presume there’s a variable conflict somewhere.
Is this a legal way to do multi-threading? Or do I have to go back to using different functions?
…DoHeightmap0(0), DoHeightmap1(1). DoHeightmap2(2)…etc…which looks ugly and not efficient to code at all.
Unity uses an old version of Mono. It means the same variable is used as the iterator each time in the for loop. Try capturing the iterator like this.
for (int i = 0; i < 9; i++)
{
int index = i;
myThreads = new Thread(new ThreadStart( () => DoHeightmap( index )));
myThreads.Start();
}
Brilliant! Thank-you!
It makes an illogical read though, I’m starting to miss C++…