#include "stdafx.h"
#include "stdio.h"
#include <string.h>
#include <process.h>
#include <windows.h>
#define WM_MYMSG WM_USER+100
HANDLE hStartEvent; // thread start event
unsigned __stdcall ThreadFunc( void* pArguments )
{
MSG msg;
printf( "In thread.../n" );
PeekMessage(&msg, NULL, WM_USER, WM_USER+1000, PM_NOREMOVE);
if(!SetEvent(hStartEvent)) //set thread start event
{
printf("set start event failed,errno:%d/n",::GetLastError());
return -1;
}
while(true)
{
if(GetMessage(&msg,0,0,0)) //get msg from message queue
{
switch(msg.message)
{
case WM_MYMSG:
char * pInfo = (char *)msg.wParam;
printf("recv %s/n",pInfo);
if(strcmp(pInfo,"msg_9")==0)
{
delete[] pInfo;
_endthreadex( 0 );
}
delete[] pInfo;
break;
}
}
};
_endthreadex( 0 );
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread=NULL;
unsigned threadID;
hStartEvent = CreateEvent(0,FALSE,FALSE,0);
if(hStartEvent == 0)
{
printf("create start event failed,errno:%d/n",::GetLastError());
return -1;
}
ResetEvent(hStartEvent);
hThread = (HANDLE)_beginthreadex( NULL, 0, &ThreadFunc, NULL, 0, &threadID );
if(hThread==NULL)
{
printf( "create thread err!/n");
CloseHandle( hThread );
return -1;
}
WaitForSingleObject(hStartEvent,INFINITE);
CloseHandle(hStartEvent);
int count = 0;
for (;count<20;)
{
char* pInfo = new char[20]; //create dynamic msg
sprintf(pInfo,"msg_%d",++count);
if(!PostThreadMessage(threadID,WM_MYMSG,(WPARAM)pInfo,0))//post thread msg
{
printf("post message failed,errno:%d/n",::GetLastError());
delete[] pInfo;
}
Sleep(1000);
}
WaitForSingleObject( hThread, INFINITE );
CloseHandle( hThread );
return 0;
}