#ifndef MTVERITY_H_ #define MTVERITY_H_ #pragma comment(lib, "user32") #include <Windows.h> #define MTASSERT(a) _ASSERTE(a) #define MTVERITY(a) if(!(a))\ PrintError(#a,__FILE__,__LINE__,GetLastError()) static void PrintError(LPSTR linedesc, LPSTR filename, int lineno, DWORD errnum) { LPSTR lpBuffer; char errbuf[256]; #ifndef _CONSOLE char modulename[MAX_PATH]; #else DWORD numread; #endif //_WINDOWS_ FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, errnum, LANG_NEUTRAL, (LPTSTR)&lpBuffer, 0, NULL ); sprintf(errbuf, "\nThe following call failed at line %d in %s:\n\n %s\n\nReason: %s\n", lineno, filename, linedesc, lpBuffer); #ifdef _CONSOLE WriteFile(GetStdHandle(STD_ERROR_HANDLE), errbuf, strlen(errbuf), &numread, FALSE ); Sleep(5000); #else GetModuleFileNameA(NULL, modulename, MAX_PATH); MessageBoxA(NULL, errbuf, modulename, MB_ICONWARNING|MB_OK|MB_TASKMODAL|MB_SETFOREGROUND); #endif exit(EXIT_FAILURE); } #endif
下面是使用技巧:
// win32Thread.cpp : 定义控制台应用程序的入口点。 // #include <stdio.h> #include <Windows.h> #include <tchar.h> #include "mtverify.h" DWORD WINAPI ThreadProc(void* pmsg) { DWORD n = (DWORD)pmsg; Sleep(n*5000); return n * 10; } DWORD WINAPI ThreadProc1(void* pmsg) { ExitThread(100); return 0; } int _tmain(int argc, _TCHAR* argv[]) { HANDLE hThread1, hThread2; DWORD dThreadID1,DThreadId2; DWORD dExitCode1,dExitCode2; hThread1 = CreateThread(NULL,0,ThreadProc,LPVOID(1), 0, &dThreadID1); hThread2 = CreateThread(NULL,0,ThreadProc1,LPVOID(2), 0, &DThreadId2); CloseHandle(hThread1); CloseHandle(hThread2); while(1) { printf("please Enter:"); getchar(); MTVERITY( GetExitCodeThread(hThread1, &dExitCode1)); MTVERITY( GetExitCodeThread(hThread2, &dExitCode2)); if (dExitCode1 == STILL_ACTIVE) { printf("Thread 1 running\n"); } if (dExitCode2 == STILL_ACTIVE) { printf("Thread2 running\n"); } if (dExitCode1 !=STILL_ACTIVE && dExitCode2 != STILL_ACTIVE) { printf("Thread Two End\n"); break; } } printf("%d,%d\n",dExitCode1, dExitCode2); system("pause"); return 0; }