- Undocumented Matlab - https://undocumentedmatlab.com -

Explicit multi-threading in Matlab part 2

Posted By Yair Altman On February 26, 2014 | No Comments

Last week, I explained [1] how we can start asynchronous Java threads to run in parallel to the main Matlab processing. Today I continue the series by examining .Net threads. Next week I will discuss C++ threads, followed by a final article on timers and process-spawning.
I continue using last week’s example, where we compute some data, save it to file on a relatively slow USB/network disk, and then proceed with another calculation. The purpose of multi-threading would be to offload the I/O onto a separate thread, so that the Matlab computation can continue in parallel without needing to wait for the slow I/O.
Dot-Net (.Net), like Java and C++, also enables multithreading. .Net libraries (assemblies) are commonly distributed as DLL files, which can be loaded into Matlab using the NET.addAssembly function, similarly to the javaaddpath function for Java classes. Using these assemblies in Matlab is then as straight-forward as in Java:

data = rand(5e6,1);  % pre-processing (5M elements, ~40MB)
start(My.NetThread('F:\test.data',data));  % start running in parallel
data = fft(data);  % post-processing (.Net I/O runs in parallel)

As with Java, the assembly only needs to be loaded once per Matlab session, not repeatedly. The definition of the .Net class closely follows that of the Java class. Unfortunately, .Net’s System.Threading.Thread [2] class is sealed (non-inheritable), so we cannot extend it as we did in Java. However, we can instantiate an internal Thread object within our class and use it. Here is the corresponding C# source code (thanks to Ronnie Shmuel who assisted):

using System;
using System.IO;
using System.Threading;
namespace My
    public class NetThread
        string filename;
        double[] doubleData;
        Thread thread;
        public NetThread(string filename, double[] data)
            this.filename = filename;
            this.doubleData = data;
            thread = new Thread(this.run);
        public void start()
            thread.Start();  // note the capital S in Start()
        private void run()
                BinaryWriter out = new BinaryWriter(
                for (int i = 0; i < doubleData.Length; i++)
            catch (Exception ex)

Note that C# Thread uses the Start() method (uppercase S), unlike java.lang.Thread that uses start() (lowercase s). Also, while java.lang.Thread.start() always invokes a run() method (the "run" name is predefined), C# Thread.Start() can invoke any delegate method. In this example I chose to name it run() for consistency with the Java example, but in fact I could have named it anything else.
In this example I've used C# source code, but in fact I could also use C++, F# or VB code, since the System.Threading.Thread class behaves very similarly in all of them. Once we compile it in our favorite compiler [hmmm, Microsoft Visual Studio anyway...], the resulting .Net assembly aught to work exactly the same in Matlab.

Compatibility and synchronization

Unlike Java and C++, .Net is not platform-independent: it only works on Windows, so if we need a cross-platform solution then we need to use Java or one of the other alternatives.
Also note that the .Net solution will only work on platforms that installed .Net of a supporting .Net version (Framework). .Net is commonly installed on Win7+, but not for example on XP. On Windows platforms where .Net is not installed, we need to download and install it before we can use any .Net features (duh!). To ensure .NET is supported on our current platform, use the NET.isNETSupported function:

>> NET.isNETSupported  % returns true/false
ans =

As with Java, when compiling a .Net class that should be used within Matlab, we must ensure that we are compiling for a .Net Framework that is equal to or lower than what Matlab will actually use in the target platform, as reported by System.Environment.Version:

% My system uses .Net 4.0, so we should compile for .Net 4.0, not 4.5
>> char(System.Environment.Version.ToString)
ans =

As with Java threads, .Net threads are most effective when they can run independently of Matlab and of each other. I do not know of any mechanism for data synchronization between .NET threads and Matlab. However, we can use one of the standard IPC mechanisms, as I shall discuss in a future article. For example, it is possible to open a COM connection to the invoking Matlab [3] (serving as an automation server) and then use it in the .Net code [4].

Categories: Low risk of breaking in future versions, Undocumented feature

Article printed from Undocumented Matlab: https://undocumentedmatlab.com

URL to article: https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part2

URLs in this post:

[1] explained: http://undocumentedmatlab.com/blog/explicit-multi-threading-in-matlab-part1/

[2] System.Threading.Thread: http://msdn.microsoft.com/en-us/library/system.threading.thread(v=vs.100).aspx

[3] open a COM connection to the invoking Matlab: http://www.mathworks.com/help/matlab/matlab_external/connecting-to-an-existing-matlab-server.html

[4] use it in the .Net code: http://www.mathworks.com/help/matlab/matlab_external/call-matlab-function-from-a-c-client.html

[5] Explicit multi-threading in Matlab part 1 : https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part1

[6] Explicit multi-threading in Matlab part 3 : https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part3

[7] Explicit multi-threading in Matlab part 4 : https://undocumentedmatlab.com/articles/explicit-multi-threading-in-matlab-part4

[8] Multi-threaded Mex : https://undocumentedmatlab.com/articles/multi-threaded-mex

[9] Multi-line uitable column headers : https://undocumentedmatlab.com/articles/multi-line-uitable-column-headers

[10] Multi-column (grid) legend : https://undocumentedmatlab.com/articles/multi-column-grid-legend

Copyright © Yair Altman - Undocumented Matlab. All rights reserved.