MATLAB Answers

How to do Multi threading in Matlab.

65 views (last 30 days)
Musab Farooq
Musab Farooq on 17 Nov 2017
Answered: Walter Roberson on 17 Nov 2017
Hello! I am taking data from serial port and storing in linked List. I want to to do some processing on data in parallel. I think the way to do is multi threading. One thread storing data and other doing processing. But I can not find any technique to do multi threading in MATLAB. Can you guys help me with this. Thanks

Answers (1)

Walter Roberson
Walter Roberson on 17 Nov 2017
MATLAB does not support linked lists very well, but they can be simulated. The simulation method can be important to performance.
The tools for multi-threading are in the Parallel Processing Toolbox. Because of the communications overhead, it can turn out to be less efficient to use parallel processing, if the amount of work to be done per call is not high enough.
Note that it is not possible to access the display from within any of the parallel operations.
The most direct implementation of multiple threads is to use spmd and use labSend and labReceive to communicate between the workers. spmd is implemented with MPI (Message Passing Interface).
I wonder, though, whether your situation might be better served by using parfeval() to start processing of tasks from the main routine, collecting their output later. parfeval() is not really suitable for communicating between workers: it is more for the case where the tasks are independent.
As of R2017a, parallel workers can communicate back to the main routine by using data queues and pollable data queues; it is also possible for the main routine to send data to the workers, but it is a bit more awkward to set up.
Often, though, when the matter has to do with data collection and processing, the preferred method to proceed is to use callbacks on the data collection that notify when a new set of data is ready; the callback process (automatically) temporarily suspends processing, then adds it to the appropriate data structure, and ends, and the regular processing of the data content resumes, eventually proceeding on to the next chunk of data. This has lower overhead than parallel processing does, so going parallel is typically only used when the processing of any one chunk is likely to take longer than the data collection interval, requiring that chunks be analyzed in parallel to avoid the queue growing to overfill memory or to avoid having processing postponed beyond the required response time. (If you are doing real-time processing then there are special toolboxes for that.)

Community Treasure Hunt

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

Start Hunting!

Translated by