View License

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Highlights from
Mex Multithreading

4.8 | 4 ratings Rate this file 19 Downloads (last 30 days) File Size: 3.11 KB File ID: #21233 Version: 1.0

Mex Multithreading


Dirk-Jan Kroon (view profile)


26 Aug 2008 (Updated )

Example of (Windows) multi-threading in a MEX file

| Watch this File

File Information

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.

MATLAB release MATLAB 7.6 (R2008a)
Other requirements Windows OS
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (5)
07 Apr 2012 shlomi golubev

excellent! Thanks a lot

16 Apr 2010 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.

16 Sep 2009 Jveer

Jveer (view profile)

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

Comment only
29 Aug 2008 A B

Excellent introduction to multithreading inside a mex function.

26 Aug 2008 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

28 Aug 2008

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

Contact us