
new&delete in different threads
Hi;
I need to pass information among threads.
Can I create something with new in one thread and delete it in another
thread.
In my case, when I delete it, the original thread has already died. Can
I do this.
It seems that I cannot. I get debug error on 'delete' line of code.
If I cannot 'new' in one thread and 'delete' in another thread, then how
should I pass information between threads?
My code is like this:
char * gpMsg = NULL; //global
CRITICAL_SECTION gCriticalSection; //global
typedef struct tagThreadMsg
{
UINT iID;
UINT iData;
Quote:
}THREADMSG;
UINT CMyApp::ThreadTwo() //this is a static thread function
{
if ( gpMsg != NULL )
{
delete[] gpMsg; //I got error here, saying:
//Debug Error!
//DAMAGE: after Normal block(#84) at
0x00DB1B80
}
THREADMSG ThreadMsg;
ThreadMsg.iID = 2;
ThreadMsg.iData = 0;
EnterCriticalSection(&gCriticalSection); //already initialized
gpMsg = new char (256);
memcpy(gpMsg, &ThreadMsg, sizeof(THREADMSG));
CString StrMsg = _T("I am in ThreadOne");
strcpy(gpMsg+sizeof(THREADMSG), StrMsg);
//pThreadOne is another CWinThread object
pThread->PostThreadMessage(IDM_THREAD_MSG, (WPARAM)gpMsg, NULL);
LeaveCriticalSection(&gCriticalSection); //already initialized
return 0;
Quote:
}
void CMyApp::OnThreadMessage(void * spMsg)
{
//This is in ThreadOne
EnterCriticalSection(&gCriticalSection);
THREADMSG * pMsg = (THREADMSG*)spMsg;
UINT iData = pMsg->iData;
UINT iID = pMsg->iID;
LPCTSTR pData = pMsg+sizeof(THREADMSG);
MessageBox(NULL, pData, NULL, MB_OK); //It works OK here.
LeaveCriticalSection(&gCriticalSection);
Quote:
}
Thanks in advance.
frank