File Exchange

image thumbnail


version 1.3 (6.34 KB) by

Using std::thread in MEX files for expensive data processing without freezing Matlab.



View License

Ever wanted to run an expensive processing task in the background without freezing Matlab (which is the case with caller functions)?

An example would be to acquire images from a camera as fast as possible, and do expensive processing (such as object detection/regocnition) in the background without dropping frames.

This submission demonstrates how to do this using std::threads from within a MEX file.

As an example, random images are acquired as fast as possible, while a straight forward (e.g. slow) Gaussian Blur operation is performed in the background.

A C++ base class (MexThread.h) together with a Matlab class wrapper (MexThread.m) provides means to achieve background threading with minimal code (GaussianBlurThread.cpp).

The code can be compiled with the first cell in demoGaussianBlurThread.m. The second cell is the demo script which acquires data in a while(true) loop, and blurs as many of the acquired frames as possible in the background.

MatlabImage.h contains a simple template image class usable in MEX files. GaussianBlur.h implements a simple Gaussian blur filtering.

Feedback / suggestions more than welcome. If parts of the code need more comments, please tell me so.

Note: this requires a C++ compiler with C++11 (formerly known as C++0x) support. Ubuntu 12.04 works right out of the box, Visual Studio 2010 would require third-party implementation of std::thread.

Comments and Ratings (2)

Thomas Weibel

You can find a commercial implementation here:
but it's quite expensive ..

Apparently std::thread is also available in a recent release of mingw:

Jan Simon

Jan Simon (view profile)

And where can I get third-party implementations of std::thread? Is there a free version, which I can use for functions published here?



Minor fixes.

MATLAB Release
MATLAB 7.12 (R2011a)

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

» Watch video