abelbop
abelbop

Reputation: 13

Call MEX function without blocking main thread

In my Matlab code, I call a MEX function that takes a few seconds to execute (feature extraction with Caffe, http://caffe.berkeleyvision.org/). I was wondering if there is a way of calling this function without blocking Matlab's main thread, so I can run other Matlab commands simultaneously while waiting for it to finish.

Would it be possible, for example, to launch the MEX call in another thread the Parallel Computing Toolbox?

Upvotes: 1

Views: 542

Answers (1)

chappjc
chappjc

Reputation: 30589

Without editing the MEX file, one way is with batch:

c = parcluster();
job = batch(c, @myMEXfun, numOutputs, {myinput1,myinput2});
% do something else in MATLAB
job.wait();
out = job.fetchOutputs();

There are also possibilities with parfeval:

p = gcp();
f = parfeval(@myMEXfun, numOutputs, myinput1, myinput2);
% do something else in MATLAB
out = fetchOutputs(f); % Blocks until complete

They both allow asynchronous execution.

This can also be done without the Parallel Computing Toolbox, but with significant changes to the MEX file source to create a thread and with additional syntax to check for completion and retrieve outputs.

Upvotes: 1

Related Questions