双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

请教如何在两个线程之间通过引用变量来传递数据?

hyacinth531 hyacinth531 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
各位好:
我编了两个线程程序,一个用来接受数据,另一个用来发送数据.具体说,接受数据的线程收到数据后将该数据运用发送数据线程发送出去.程序如下:
接受数据线程:
"
这是接受数据线程
class ReceiveRobInf : public ArASyncTask
{
protected:
int port;//port use to send message
socklen_t sin_len1;
char message[5];//message[256]; 6.2
int socket_descriptor;
struct sockaddr_in sin;
double myformationtype;

struct ReceiveData
{
char header[4];
double myflag;
};

public:

ReceiveRobInf(int port, double* formationtype);//-----------------(1)
~ReceiveRobInf();
void* runThread(void*);
};
ReceiveRobInf::ReceiveRobInf(int port, double* formationtype):ArASyncTask ()
{//port is port used to receive network information
port=port;

bzero(&sin,sizeof(sin));//use to receive message 6.2
sin.sin_family=AF_INET;
sin.sin_addr.s_addr=htonl(INADDR_ANY);
sin.sin_port=htons(port);
sin_len1=sizeof(sin);
/*create a UDP socket*/
socket_descriptor=socket(AF_INET,SOCK_DGRAM,0);
bind(socket_descriptor,(struct sockaddr*)&sin,sizeof(sin));

myformationtype=*formationtype;


}

void* ReceiveRobInf::runThread(void*)
{
ReceiveData receivedata;

while(this->getRunningWithLock())
{
myMutex.lock();
printf("receive date from other robot!\n");

recvfrom(socket_descriptor,&receivedata,sizeof(receivedata),
0,(struct sockaddr *)&sin,&sin_len1);
//在此处接收数据-------------------------------------------------(2)
myformationtype=receivedata.myflag;
printf("other robot information'flag is %f!\n\n",receivedata.myflag);
myMutex.unlock();
}
"
类似的用发送数据线程
"
SendToR(double* formationflag ,ArRobot*robot, int port , char ip[])

"
主函数像这样调用为:
"
main()
{
..
double formationflag;
ReceiveRobInf receiverobinfor(6789,&formationflag) receiverobinfor.runAsync();

SendToR sendtor(&formationflag, &robot, 6789,"192.168.1.21");
sendtor.runAsync();
..}
"
我的问题是:如何在接收线程的中定义一个变量指向其参数double* formationtype
使得在(2)处当接受线程循环收到数据后改变这个变量,同时formationflag也改变,之后通过这个引用变量将数据传给发送线程.万分感谢!!
...全文

相关推荐

评论 4
收藏 已收藏
分享
返回顶部
hyacinth531
C语言 70,039 成员 243,237 内容