image thumbnail


version (6.34 KB) by Thomas Weibel
Using std::thread in MEX files for expensive data processing without freezing Matlab.


Updated 06 Sep 2012

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.

Cite As

Thomas Weibel (2022). MexThread (, MATLAB Central File Exchange. Retrieved .

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

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!