看下面代码:
int OnGetData(int nIPCID, FeatureStatusMessage* psFeatureStatusMsg, int nDataLen, int** ppReply,
int nMsgCode) {
FeatureStatusMessage* psFeatureData = NULL;
IPCBaseStr* psCmdStr = NULL;
psCmdStr = (IPCBaseStr*)psFeatureStatusMsg;
psFeatureData = (FeatureStatusMessage*)malloc(
sizeof(FeatureStatusMessage)); // alloc memory space to store request data
memset(psFeatureData, 0, sizeof(FeatureStatusMessage));
memcpy(psFeatureData, psFeatureStatusMsg, sizeof(FeatureStatusMessage));
psFeatureData->pFeatureStatusList = new vector<FeatureStatus>;
*psFeatureData->pFeatureStatusList = *psFeatureStatusMsg->pFeatureStatusList;
m_piMsgCtrl->PostMessage((CEMsgReceiver*)m_pMsgRecv, psCmdStr->unPriority, psCmdStr->dTimeStamp,
nMsgCode, (int)psFeatureData, nDataLen);
return 0;
}
函数功能介绍:对收到的数据进行拷贝,然后post出去;
因为post出去是给另一个线程,所以第411行是用malloc生成一段堆中的内存,这样在收到的线程中才能访问.
但是这还不够,由于结构体里有一个指向vector的指针,如果不给它分配内存只是浅拷贝,接收数据的线程还是无法访问到正确的数据.所以这里又new了一段堆中的内存!完成深拷贝!
每个线程栈上的数据,其它的线程是无法访问的,只能放到堆上(或成员变量,数据段中的常量,全局变量)才能在线程间共享。