File Exchange

image thumbnail

Mex Multithreading

version (3.11 KB) by Dirk-Jan Kroon
Example of (Windows) multi-threading in a MEX file


Updated 02 Sep 2008

View License

Editor's Note: This file was selected as MATLAB Central Pick of the Week

Nowadays, Matlab is multi-threaded but most MEX files are still single threaded. This is an simple example of c-code for MEX file multi-threading.

The mex function "y = square(x)" is written in c-code and starts 2 worker threads. The first worker thread will square all values on the even input indexes x[0] x[2] .. x[n], and the second worker thread all odd indexes x[1] x[3] .. x[n]. Also demonstrates thread safety by using Mutex to lock percentage variable.

mex square.c -v;
y = square([1 2 3 4 5 6 7 8 9])

The function uses <windows.h> (function sleep ) and <process.h> ( function _beginthreadex ) which are included with visual studio and some other compilers.

This example is tested with Windows Vista 64 and Visual Studio 2008 compiler, and with (default) LCC compiler and Vista 32.

Cite As

Dirk-Jan Kroon (2020). Mex Multithreading (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (7)

I noticed that the master thread will acquire the mutex every time to read the percentage variable and release it afterwards. IMHO this just wastes time. Only the worker threads benefit from it (as they read and modify the variable).

In this case, you might want to drop the mutex and use the InterlockedIncrement() function to update the percentage.


Have you considered redoing this example using C++ since the thread support library was added to the standard in C++ 11?

excellent! Thanks a lot

Ad Client

Very well commented . There is a typo in square.c line 144 col 41 - should be double "%" to actually print out.
Tested on WinXP64bit Pro - works.


can this capability be compiled into a standalone application using the matlab compiler?


Excellent introduction to multithreading inside a mex function.

Nick Clark

Nice submission. Cute example and easy to understand. Check out Intel TBB for more scalability, especialy now it is available free of charge. Thanks again :D


Now also works with the Matlab LCC compiler.

Added Mutex example and replaced function _beginthread by _beginthreadex, which allows WaitForSingleObject in Matlab

MATLAB Release Compatibility
Created with R2008a
Compatible with any release
Platform Compatibility
Windows macOS Linux