- Home /
My plugin runs once but not twice
I have a plugin that calls C++ code. When the game starts, it calls this extern
C++ function:
void startPlugin() {
MyClass::instance = new MyClass();
MyClass::instance->process();
}
The process
method runs an infinite loop that processes data and goes on, as long at the keepRunning
member is true. Because it runs an infinite loop and blocks, this method is called within its own thread.
When the game ends I run this extern
method from C#:
void stopPlugin() {
MyClass::instance->keepRunning = false;
sleep(1); // Make sure the process loop is done. It should take less than one frame, but just to be sure...
MyClass::cleanup();
}
Which refers to this method:
void MyClass::cleanup() {
delete instance;
instance = NULL;
}
Based on what the console says, these methods are indeed run.
On Mac, this works the first time. I can start the game in the editor and stop it in the editor and everything works fine. But if I try to run it a second time without restarting the Unity editor, the whole editor freezes. Sometimes it takes three times instead of two, but invariably the second or third attempt to play freezes Unity completely. The cursor changes to the spinning pinwheel.
The log says:
Starting.
(Filename: /Applications/buildAgent/work/d63dfc6385190b60/artifacts/MacEditorGenerated/UnityEngineDebug.cpp Line: 49)
Receiving unhandled NULL exception
Launching bug reporter
Obtained 37 stack frames.
#0 0x00000090019390 in _platform_memmove$VARIANT$sse42
And then the stack trace brings up the function that calls the extern
function.
Trying to join the thread that was running startPlugin
freezes the editor on stop. I don't think it should do that. After all, at that stage, the loop is over and the instance cleaned. This is not guesswork, there are visible side effects: ending the loop turns off the computer's camera and I can see the light of the camera go off. Also a debug message is sent in C# after the call to startPlugin
returns. So there is no doubt that the loop is over.
Am I doing something obviously wrong?
Answer by eeytan · Dec 31, 2014 at 03:01 AM
I found my answer.
Even though no thread is called inside of the C++, I still need call pthread_exit(this)
at the end of the process
method. This is not necessary on Windows, but it is on Mac. After that, all works.