// ExitCode.c
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
DWORD WINAPI ThreadFunc(LPVOID);
int main()
{
HANDLE hThrd1;
HANDLE hThrd2;
DWORD exitCode1 = 0;
DWORD exitCode2 = 0;
DWORD threadId;
hThrd1 = CreateThread(NULL,
0,
ThreadFunc,
(LPVOID)1,
0,
&threadId);
if(hThrd1)
{
printf("Thread 1 launched/n");
}
hThrd2 = CreateThread(NULL,
0,
ThreadFunc,
(LPVOID)2,
0,
&threadId);
if(hThrd2)
{
printf("Thread 2 launched/n");
}
// keep waiting untill both calls to
// GetExitCodeThread succeed and
// Neither of them returns STILL_ACTIVE
for(;;)
{
printf("press any key to exit/n");
getch();
int n;
n = GetExitCodeThread(hThrd1, &exitCode1);
n = GetExitCodeThread(hThrd2, &exitCode2);
if(exitCode1 == STILL_ACTIVE)
{
puts("thread 1 is still running/n");
}
if(exitCode2 == STILL_ACTIVE)
{
puts("thread 2 is still running/n");
}
if(exitCode1 != STILL_ACTIVE && exitCode2 != STILL_ACTIVE)
{
break;
}
}
CloseHandle(hThrd1);
CloseHandle(hThrd2);
printf("thread 1 returned %d/n", exitCode1);
printf("thread 2 returned %d/n", exitCode2);
return EXIT_SUCCESS;
}
DWORD WINAPI ThreadFunc(LPVOID n)
{
Sleep((DWORD)n*10000*2);
return (DWORD)n*10;
}
/*********************************************************************************
BOOL GetExltCodeThread(
HANDLE hThread,
LPDWORD lpExitCode
);
hThread 由CreateThread()传回的线程handle
lpExitCode 指向DWORD用于接受结束代码
返回值:
如果成功返回TRUE否则FALSE 调用GetLastError()找出原因
如果线程已经结束,那么结束代码lpExitCode参数中带回来。
如果线程尚未结束,lpExitCode带回来的值是STILL_ACTIVE
*********************************************************************************/