Matlab Engine closes unexpectedly after thread ends in C++

조회 수: 1 (최근 30일)
Yung-Yeh Chang
Yung-Yeh Chang 2017년 4월 23일
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 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.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Manage Products에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by