用消息在Win32控制台程序多线程间进行通讯

 #include #include //#include //#include #define UM_MSG1 (WM_USER + 1) #define UM_MSG2 (WM_USER + 2) DWORD WINAPI Thread1(LPVOID para) { DWORD dwThreadId = *(DWORD *)para; DWORD i = 0; TCHAR *p; char strTmp[100]; while(TRUE) { Sleep(1700); p = new TCHAR[10]; sprintf_s(strTmp, 100, "Hello %d %x ", i++, p); PostThreadMessage(dwThreadId, UM_MSG1, (WPARAM)strTmp, (LPARAM)p); //delete []p; } return 0; } DWORD WINAPI Thread2(LPVOID para) { char strTmp[100]; DWORD dwThreadId = *(DWORD *)para; DWORD i = 0; TCHAR *p; while(TRUE) { Sleep(3000); p=new TCHAR[10]; sprintf_s(strTmp, 100, "World %d %x", i++, p); PostThreadMessage(dwThreadId, UM_MSG2, (WPARAM)strTmp, (LPARAM)p); //delete []p; } return 0; } int main() { printf("UM_MSG1: 0x%x/r/n", UM_MSG1); printf("UM_MSG2: 0x%x/r/n", UM_MSG2); DWORD dwValue = GetCurrentThreadId(); HANDLE hThread1 = CreateThread(NULL, 0, &Thread1, &dwValue, 0, NULL); // &Thread1可写作Thread1, 都是函数指针. HANDLE hThread2 = CreateThread(NULL, 0, &Thread2, &dwValue, 0, NULL); CloseHandle(hThread1); CloseHandle(hThread2); MSG msg; while(GetMessage(&msg, NULL, 0, 0)) { switch(msg.message) { case UM_MSG1: case UM_MSG2: printf("msg: 0x%x w: %x ws: %s l: %x/r/n", msg.message, &msg.wParam, msg.wParam, msg.lParam); delete [](TCHAR *)msg.lParam; //注释掉这句你就会看到堆内存地址变化 break; default: printf("Unknown msg:0x%x/n",msg.message); break; } Sleep(1); } return 0; }

 

// 代码由"zyq5945"在http://topic.csdn.net/u/20091106/10/882619b7-094a-45dc-ba1e-2f0888d15650.html中提供.

你可能感兴趣的:(C/C++)