Multithread inside class method
2 次查看(过去 30 天)
显示 更早的评论
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
回答(1 个)
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!