Instructables

Matlab Multithreading, EASY

Picture of Matlab Multithreading, EASY
making a multithreaded matlab program in five minutes:

matlab is excellent, it makes it very easy to do things that would be very compicated and annoying in lower level languages (e.g. c++). The main large flaw of matlab is that it does not _inherently_ support multithreading. HOWEVER, by integrating matlab with c++ code we can combine the advantages of matlab with the huge advantage of multithreading. We do this by using 'mex functions'.

Note: for a tiny bit of background in making mex function see my previous instructable:
http://www.instructables.com/id/Making-a-Matlab-MEX-file/

Note: Basically multithreading allows one to have different sections of code running in parallel. For example one section could be in a loop waiting for keyboard input while another section is doing other stuff.
 
Remove these adsRemove these ads by Signing Up

Step 1: Code

Picture of code
you will need matlab and a plain text editor: use either notepad which comes with windows (search for notepad.exe) or use the matlab m file editor (file-new-mfile). This worked with matlab 6.5 (R13) and with matlab 7 (R14) but I'm having trouble using it with matlab r2007a.

1) download the code and wav file attached to this step (Code And Wav File.rar), this is a compressed file, you'll need winzip or winrar to uncompress it. NOTE: because instructables is slightly retarded this file will download as something like FLSKW9EFHIK6H6V.tmp, so you'll have to rename it to something.rar (annoying, but not my fault).
2) save both of these (code and wav file) in your matlab 'work' directory (makes things easier)
3) open matlab
4) type in mex mythreadprog.cpp
4.5) NOTE: if this is the first time you're using the mex compiler in matlab, type mex -setup before step 4 to choose the compiler you want to use.
5) when I do this on my matlab I get a 'command line warning', but it doesn't effect anything
6) type in hullo=1, this initializes a variable used by the mex file (if you don't do this matlab will crash)
7) to run the mex file type in mythreadprog

8) on the matlab prompt you will see Val #
where # is the value of hullo, you will also hear the wav file play 7 times, the time between each playing of the wav file is (1second * hullo), so as you hear the sound being played you can change the value of hullo (hullo=5, hull=3, etc) and you can hear the mex thread taking this into account (there will be different length pauses as you change the hullo value in matlab)
Note that matlab returns control to you imediately even though the thread is still running in the background.

9) if you want the thread to print the changing values at matlab's prompt you can uncomment _both_ of the lines labled //----for testing---- in the code

Note: if you only uncomment the mexPrintf in the thread and not the sleep in the mexFunction matlab will crash. This is because you're sending a callback to matlab after the mexFunction has ended. If you want to have the thread send information back to matlab after the mexFunction has stopped it's more compicated (aka. I don't know how, look it up on google).

#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <process.h> //used for thread
#include "mex.h"
#include <mmsystem.h> //used for sound
#pragma comment(lib, "winmm.lib") //used for sound

void cdecl MyThread(LPVOID pVoid);

//######################################################
//##############--main mex function--########################
//######################################################
void mexFunction(int nlhs, mxArray *plhs,
int nrhs, mxArray *prhs[])
{
int ThreadNr; //needed for the thread

//start your thread
_beginthread( MyThread, 0, &ThreadNr );

//----for testing----
//Sleep(20000); //will make the mex function stay around for 20 seconds so you can see the mexPrintfs of the thread if you want
}

//################################################
//##########--Thread Code--#########################
//################################################
void cdecl MyThread(LPVOID pVoid)
{
//declare your variables/pointers
int x=0; //used to adjust # of while loops
const mxArray *myarray; //used to help extract your matlab variable's value
double *TempPointer; //used to help extract your matlab variable's value
double Val; //holds the value of your matlab variable

//----Setup your pointers before entering the thread's loop, in this way we will not have to talk
//----to matlab at all once we enter the thread (we will be simply accessing the matlab
//----variables memory location). This is useful because a lot of really fast communication with
//----matlab can crash it.
//get a pointer to a pointer to the hullo variable (which you should initialize in matlab before running this prog)
myarray = mexGetVariablePtr("base", "hullo"); //can be base caller or global
//get the hullo variable's value from the pointers, store it in Val
TempPointer = mxGetPr(myarray);

while(x<10)
{
x++;

//here we are accessing the matlab variable's memory location without having to talk to matlab
Val = *TempPointer;

//play a sound
PlaySound("alleluia.wav", NULL, SND_FILENAME | SND_SYNC);
//wait in between sounds for Val seconds
Sleep(1000*Val);

//----for testing----
//mexPrintf(" Val:%f", Val);
}
}
Dennisz2 years ago
Hi everybody,
I want to provide a solution for the above illustrating error messages.

First of all here are the corrections of the error:
- L11 and L33 expecting ";" : substitute cdecl by _cdecl or _stdcall (is also taken for calling)
- L19 "redeclaration..." : substitute
void mexFunction(int nlhs, mxArray *plhs,int nrhs, mxArray *prhs[]) by
void mexFunction(int nlhs, mxArray *plhs[ ],int nrhs, const mxArray *prhs[])

These corrections should solve the above mentioned problems. To me one new problem appeared in respect to the winmm.lib and playing the sound file. It seems the sound library "winmm.lib" won't be linked to the rest of the code which leads to the following error:

Writing library for mythreadprog.mexw32
c:\docume~1\studi\locals~1\temp\mex_4y~1\mythreadprog.obj .text: undefined reference to '_PlaySoundA@12'

How can I resolve that error? The library in the batch file within the user settings of Matlab/MEX is already including the winmm.lib. I used the default LCC-compiler.

Thanks and regards,
Dennis
Txomin3 years ago
It works! Thank you very much. Aaaaaaaleluya!! ;)
ann7ita3 years ago
I downloaded the code i tried to run it and i get this result

mex mythreadprog.cpp

Error mythreadprog.cpp: 11 syntax error; found `MyThread' expecting `;'
Error mythreadprog.cpp: 19 redeclaration of `mexFunction' previously declared at .\mex.h 135
Warning mythreadprog.cpp: 23 assignment of pointer to void function(pointer to void) to pointer to int function(pointer to void)
Error mythreadprog.cpp: 33 syntax error; found `MyThread' expecting `;'
Warning mythreadprog.cpp: 58 missing return value
Error mythreadprog.cpp: 33 undefined size for `void cdecl'
4 errors, 2 warnings

C:\PROGRA~1\MATLAB\R2007B\BIN\MEX.PL: Error: Compile of 'mythreadprog.cpp' failed.

Do you think that i have any trouble with my compiler?
Thanks for any reply.
ll.136 years ago
Hey! you're back&alive. =) 'tis good
Pro

Get More Out of Instructables

Already have an Account?

close

PDF Downloads
As a Pro member, you will gain access to download any Instructable in the PDF format. You also have the ability to customize your PDF download.

Upgrade to Pro today!