- Home /
Memory Leak caused by Multi Threading
I am creating a board game similar to tic tac toe, and I've created an AI to play that game. The AI is very CPU intensive, so I decided to put it on it's own thread. I'm using this plugin to do multithreading: https://www.assetstore.unity3d.com/en/#!/content/15717 .
I have this IEnumerator:
static IEnumerator executeAITurn(Turn turn) {
Vector2[] move = mctsManager.mcts(new State(sections, null, turn), AIIterations)[0, 0].metaData.lastMove;
yield return Ninja.JumpToUnity;
input(move, true);
yield return Ninja.JumpBack;
Debug.Log("DONE!");
}
and I run it using
gameManager.StartCoroutineAsync(executeAITurn((AITurn == Turn.X) ? Turn.O : Turn.X));
Normally when I run executeAITurn it works normally without problems, but for some reason sometimes when I run it, it does what it's supposed to but in task manager my memory just increases by 200 mb, and stays there. After that as I continue running executeAITurn the memory just keeps on increasing to like over 1000 mb, and then gets extremely slow.
Another thing is that if I click the play button again to stop the game, the memory still stays that high.
Any help would be appreciated.
EDIT:
mctsManager Class: https://pastebin.com/yzeHrY2p
input Function: https://pastebin.com/8f2hzZws
Answer by ShadyProductions · Jul 17, 2017 at 01:33 PM
You are constantly creating new states: new State(sections, null, turn)
which creates a new object everytime and cause memory to heap up.
Instead you could create one state, and edit the state the next time. Like so:
static State stateData = new State();
static IEnumerator executeAITurn(Turn turn) {
//change existing state
stateData.Sections = sections;
stateData.SecondVar = null;
stateData.Turn = turn;
Vector2[] move = mctsManager.mcts(stateData, AIIterations)[0, 0].metaData.lastMove;
yield return Ninja.JumpToUnity;
input(move, true);
yield return Ninja.JumpBack;
Debug.Log("DONE!");
}
That might have some performance improvement. Other than that you're not providing enough information for us to see what is causing this. For example what is your input method what does mctsManager.mcts do? etc..
I added the code for mcts$$anonymous$$anager and the input function to question.
After looking into mcts$$anonymous$$anager I'm noticing that I do use new State() and new Section[] a lot. So is the solution to make single variables for all those situations, that I just change when I need to?
It's always going to be better, but not sure if the difference in performance will be huge. It's hard to say where it's co$$anonymous$$g from, have you profiled the game using the unity performance profiler, you can see where the spikes are co$$anonymous$$g from.
I used the profiler, but I'm not sure how to use it to track where the spikes are co$$anonymous$$g from. like I see the total memory allocated slowly increasing, but I'm not sure how to find the cause for it using the profiler.