Updated
(Because my original condition is no longer appropriate after several tests, I changed the code example to better describe the problem)
Long story short, the Matlab engine opened in the thread in my C++ application closed unexpectedly after the thread ends without calling engClose()
explicitly. I hope anyone can help me solve the mystery and find a way to better control the engine.
The detail described as follows
I know that Matlab Engine API is not thread-safe. But for windows, I figure that with engOpenSingleUse()
, multi-threaded may still be achievable. The idea here was to have the calculations from different objects (classes) operate on the same Matlab computational engine while they were in the same thread. Each thread then accesses its own interface which contains a valid Matlab engine pointer among those objects. and therefore, avoid conflict in my multi-thread application. Then I bumped in to this issue. The Mmatlab Engine closed itself after the thread ended, without calling engClose()
.
For testing purpose, I would want those Matlab engines remain open so I can perform additional checks and operations by entering code directly in the consoles.
After many tests, I finally realized that it's not about how I implement the Matlab engine because simply calling engOpen()
or engOpenSingleUse()
in thread would result in this issue.
Here is an example I use for test
#include<memory>
#include<thread>
#include<map>
#include<engine.h>
void callback() {
Engine* ep = engOpenSingleUse(NULL,NULL,NULL);
}
int main(int argc, char *argv[])
{
std::shared_ptr<std::thread> thread1;
thread1 = std::make_shared<std::thread>(&callback);
std::shared_ptr<std::thread> thread2;
thread2 = std::make_shared<std::thread>(&callback);
thread1.join();
thread2.join();
return 1;
}
The code compiled and ran fine. Two instances of Matlab engines started and ran as expected. But somehow the Matlab engine I started along the thread closed itself without calling engClose();
.
If I didn't call the callback()
using the thread
, e.g.
void main() {callback();}
the application ends with an opened Matlab engine, which is totally expected. But using the thread, all Matlab engines closed automatically.
Have anyone even encountered similar problem? I would like those instances remain open unless I instruct the close signal explicitly, otherwise I could lose control in my management class because the engine closes unexpectedly. Any thought is appreciated.
Edit
As a comment pointed, I don't need shared_ptr
in this case. But the truth is that it is somehow necessary in my real implementation. The simple example here may seem to be unnecessary,though. Anyhow, in case you wonder, I did try
std::thread thread1(callback);
std::thread thread2(callback);
thread1.join();
thread2.join();
The result is complete the same. So using the pointer or not is definitely not the issue here.