Multithread inside class method

조회 수: 2 (최근 30일)
Bandar
Bandar 2021년 6월 28일
편집: Mohammad Sami 2021년 6월 29일
I would like to implment a project for teleoperation task in robotics. In C++, I can create a class with method that keeps listening to TCP/IP packets in an independent thread. I would like to create same scenario with matlab. I couldn't find guidelines for this in Matlab. See the following simple class. I would like isDataReceived() to be run in an independent thread. In the main thread, the robot does other stuff. I've seen the callback function in events block but this needs to be triggered. I need this because the received data needs to be maninpulated. Any suggestions?
classdef Robot < handle
properties
m_server = tcpserver("127.0.0.1",5000);
m_buffer = [];
end
methods (Access = private)
function flag = isDataReceived(this)
if this.m_server.NumBytesAvailable
this.m_buffer = read(this.m_server,this.m_server.NumBytesAvailable,"string");
flag = true;
else
flag = false;
end
end
end
end
  댓글 수: 2
Mohammad Sami
Mohammad Sami 2021년 6월 29일
Do you have Parallel Computing toolbox ?
Bandar
Bandar 2021년 6월 29일

댓글을 달려면 로그인하십시오.

답변 (1개)

Mohammad Sami
Mohammad Sami 2021년 6월 29일
편집: Mohammad Sami 2021년 6월 29일
You can use a combination of parfeval and data queue object to run your TCP server in parallel. You can write a function that reads data from TCP server object. You can then have this function process the data and put the processed output into the data queue. On the data queue you can set a callback which will then do something with the processed output. You can then call this function using parfeval so that it runs in a separate thread. If you want the reading function to keep running, you can use a while loop inside your function. The other option is to parfeval the reading function inside the callback. So once the processed data is received. The callback starts the next read before it does other things.
You can see my earlier answer which gives an example of how you can build something like above. https://www.mathworks.com/matlabcentral/answers/793972-send-and-recieve-data-between-client-and-workers?s_tid=srchtitle

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by