请教如何在两个线程之间通过引用变量来传递数据?
各位好:
我编了两个线程程序,一个用来接受数据,另一个用来发送数据.具体说,接受数据的线程收到数据后将该数据运用发送数据线程发送出去.程序如下:
接受数据线程:
"
这是接受数据线程
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也改变,之后通过这个引用变量将数据传给发送线程.万分感谢!!
[解决办法]
用全局变量不行么