Print to MATLAB command window from mex file and another thread

Viewed 174

I modified a sample program to demonstrate the issue: It prints a string each second. The problem is that the messages appear in the command window after MATLAB returns to idle state (all at once). If it is called from the command line and MATLAB returns to idle, the messages appear in the command window:

mexFile;

But in this case:

mexFile; while 1; end;

The messages appear after I abort the endless loop by ^C.

Here is my source code. It uses feval("fprintf"...). A subsequent call to pause(0.001) or drawnow does not change anything.

How can I force matlab to "flush" messages to the command window?

#include "mex.hpp"
#include "mexAdapter.hpp"
#include <thread>
#include <future>    


class MexFunction : public matlab::mex::Function {
private:
    std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr = getEngine();
public:
    void print(const std::string& msg)
    {
        matlab::data::ArrayFactory factory;
        // Pass stream content to MATLAB fprintf function
        matlabPtr->fevalAsync(u"fprintf", 0,
            std::vector<matlab::data::Array>({ factory.createScalar(msg) }));
        // matlabPtr->evalAsync(u"pause(0.001);");
    }

    void DisplayDateTime() {
        matlab::data::ArrayFactory factory;
        for (int count = 0; count < 20; count++)
        {
            print("Loop " + std::to_string(count) + "\n");
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }

    void operator()(matlab::mex::ArgumentList outputs,
        matlab::mex::ArgumentList inputs) {
        mexLock();
        voidStdFuture = std::async(std::launch::async,
            &MexFunction::DisplayDateTime, this);
    }
};
0 Answers
Related