首页 > 代码库 > 多线程实现消息通信
多线程实现消息通信
多线程实现消息通信
在测试学习线程创建及通信过程中,测试多种方式,感觉此种较为简单易懂实用
#include <stdio.h> #include <windows.h> struct info { HWND hWnd; DWORD dwThreadId; char* thing; }; DWORD WINAPI ThreadFun(LPVOID lpParam);// Main Thread DWORD WINAPI Thread1(LPVOID lpParam); // Sub Thread int main() { info Info; char th[] = "somthing"; Info.hWnd = GetActiveWindow();//GetSafeHwnd(); // get current HWND Info.thing = th; DWORD dwThreadID; HANDLE hThread = CreateThread(NULL,0, ThreadFun,&Info, NULL,&dwThreadID); Info.dwThreadId = dwThreadID; WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); HANDLE hCurrentProc = GetCurrentProcess(); printf("%08X %08X\n", hThread, hCurrentProc); return 0; } DWORD WINAPI ThreadFun(LPVOID lpParam) { info* Info = (info*)lpParam;//传递的消息结构体 printf("Thread Start!!!!!\n"); printf("ThreadID %d\n", Info->dwThreadId);// MSG msg; info mInfo; mInfo.dwThreadId = GetCurrentThreadId(); HANDLE hThread1 = CreateThread(NULL,0, Thread1, &mInfo, NULL, NULL); printf("SomeThing %s\n", Info->thing);
//主线程实现消息检测循环,当接收退出信息退出循环 while(1) { PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); if(msg.message == WM_QUIT) { printf("\nGet message(Quit) from Thread1\n\n"); CloseHandle(hThread1); break; } } printf("Thread Over!\n"); return 0; } //子线程 DWORD WINAPI Thread1(LPVOID lpParam) { info* Info = (info*)lpParam; printf("\n\tThread1 Start!!!!!\n"); printf("\tThis ThreadID(%d) is MainThreadID!!!!!\n", Info->dwThreadId); printf("\tThread1ID %d\n", GetCurrentThreadId()); int ret = PostThreadMessage(Info->dwThreadId, WM_QUIT, NULL, NULL); if(ret == ERROR_INVALID_THREAD_ID) printf("\tpostthreadmessage Fail!!!!!\n"); else printf("\tret: 0x%08x\n", ret); return 0; }
多线程实现消息通信
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。