Calling matlab mex from parfeval
7 views (last 30 days)
Show older comments
I have an existing matlab mex program that I want to alter to run from a thread. The matlab mex works properly when called from the main thread (command line) in MATLAB. I implemented the following
pool = backgroundPool();
q = parallel.pool.DataQueue();
for (ii=1:4000)
if (ii==1000)
parfeval(pool,@mex_thread,1,my_struct,q);
afterEach(q, @disp); % Need this to print messages
end
pause(0.001); % thread does not run until main script stops without this
end
function [retval] = mex_thread(my_struct,q)
send(q,sprintf('Got to point 1\n'));
for (idx=1:100)
send(q,sprintf('Got to point 2\n'));
my_mex_program(my_struct);
send(q,sprintf('Got to point 3\n'));
end
end
I simplified the mex program to this:
class MexFunction : public matlab::mex::Function {
public:
void operator()(ArgumentList outputs, ArgumentList inputs) {
return;
}
};
But I only get this on the console, indicating that the mex did not return
Got to point 1
Got to point 2
How do I go about determining what is wrong? Is it legal to call mex from a background thread?
0 Comments
Answers (1)
Christopher Mirfin
on 9 Sep 2025
Edited: Christopher Mirfin
on 9 Sep 2025
Unfortunately, calling MEX from a thread-based pool (in this case backgroundPool) is not currently supported. So for now, you must use parpool("Processes") to create a process-based pool if you have access to Parallel Computing Toolbox.
As a note, errors associated with parfeval are captured on the return output object, a parallel Future, i.e.
future = parfeval(pool,@mex_thread,1,my_struct,q);
Using fetchOutputs on this future will wait for the work to complete and throw any associated errors. Or, if you want to report the error asynchronously, use a continuation afterEach with the PassFuture=true option.
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!