File Exchange Pick of the Week

Our best user submissions

Mex Multithreading 2

Posted by Sean de Wolski,

Sean‘s pick this week is Mex Multithreading by Dirk-Jan Kroon.

My pick this week is an example of how to write multithreaded MEX functions to take advantage of more of your computational cores. MEX function allow you to include C/C++ or Fortran code directly in MATLAB.

Since I don’t write very much C code myself (I usually cheat and use MATLAB Coder) it’s nice to see a simple example of how to accomplish a specific task in MEX. Dirk-Jan shows the header files to include (Windows only!) and the process for executing on multiple threads and using a mutex between them to update a percentage complete.

By using multiple threads, you can expedite the C code and not have to make memory copies like you would have to by using Parallel Computing. I do a lot of Parallel Computing but some times am asked how to do both multithreading AND parallel computing together. You might want to do both if you have fewer jobs to run than cores available or if memory requirements are high. This is a good example of one way to go about that. You could compile the MEX function and then call it inside of your favorite parallel construct. Of course, many MATLAB functions are already multithreaded so often it will happen implicitly.

Here’s a look at my Task Manager while running square so you can see the different threads in action. square is also updating the percentage to the command line as it goes.

y = square(magic(500));
finished: 0 
finished: 0 
finished: 0
:
//snip for brevity//
:
finished: 99 
finished: 99 

Do you write C/C++ and need to pull it into MATLAB? Have you used multithreading from within MEX and have any pro-tips to offer?

Give it a try and let us know what you think here or leave a comment for Dirk-Jan.

Get the MATLAB code

Published with MATLAB® R2017b

2 CommentsOldest to Newest

Royi replied on : 1 of 2

In my opinion, the best way to use C Code in MATLAB is using DLL’s and not MEX.
You can create a code which is universal (Will create DLL in Windows, SO in Linux and Dylib in macOS) and utilize OpenMP and have Multi Threading in all operating systems.

It’s easier and more portable.

Add A Comment

Your email address will not be published. Required fields are marked *

What is 1 + 4 ?

Preview: hide