程序执行很快就结束了。SLEEP 不起作用!
thread1 is launched!
thread2 is launched!
Please input any key to eixt
thread1 exitcode is 0
thread2 exitcode is 0
请按任意键继续. . .
#define WIN32_LEAN_AND_MEAN
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>DWORD WINAPI ThreadFunc(LPVOID);int main()
{
HANDLE hThread1;
HANDLE hThread2;
DWORD threadId;
DWORD exitCode1 = 0;
DWORD exitCode2 = 0;
hThread1 = CreateThread(NULL,
0,
ThreadFunc,
(LPVOID)1,
0,
&threadId);
if(hThread1)
printf("thread1 is launched!\n"); hThread2 = CreateThread(NULL,
0,
ThreadFunc,
(LPVOID)2,
0,
&threadId);
if(hThread2)
printf("thread2 is launched!\n"); while(1)
{
printf("Please input any key to eixt\n");
getch();
if(exitCode1 == STILL_ACTIVE)
printf("thread1 is still active\n");
if(exitCode2 == STILL_ACTIVE)
printf("thread2 is still active\n");
if ((exitCode1 != STILL_ACTIVE) && (exitCode1 != STILL_ACTIVE))
break;
}
CloseHandle(hThread1);
CloseHandle(hThread2);
printf("thread1 exitcode is %d\n",exitCode1);
printf("thread2 exitcode is %d\n",exitCode2); return EXIT_SUCCESS;
}DWORD WINAPI ThreadFunc(LPVOID n)
{
Sleep((DWORD)n*1000*10);
return ((DWORD)n*10);
}
thread1 is launched!
thread2 is launched!
Please input any key to eixt
thread1 exitcode is 0
thread2 exitcode is 0
请按任意键继续. . .
#define WIN32_LEAN_AND_MEAN
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>DWORD WINAPI ThreadFunc(LPVOID);int main()
{
HANDLE hThread1;
HANDLE hThread2;
DWORD threadId;
DWORD exitCode1 = 0;
DWORD exitCode2 = 0;
hThread1 = CreateThread(NULL,
0,
ThreadFunc,
(LPVOID)1,
0,
&threadId);
if(hThread1)
printf("thread1 is launched!\n"); hThread2 = CreateThread(NULL,
0,
ThreadFunc,
(LPVOID)2,
0,
&threadId);
if(hThread2)
printf("thread2 is launched!\n"); while(1)
{
printf("Please input any key to eixt\n");
getch();
if(exitCode1 == STILL_ACTIVE)
printf("thread1 is still active\n");
if(exitCode2 == STILL_ACTIVE)
printf("thread2 is still active\n");
if ((exitCode1 != STILL_ACTIVE) && (exitCode1 != STILL_ACTIVE))
break;
}
CloseHandle(hThread1);
CloseHandle(hThread2);
printf("thread1 exitcode is %d\n",exitCode1);
printf("thread2 exitcode is %d\n",exitCode2); return EXIT_SUCCESS;
}DWORD WINAPI ThreadFunc(LPVOID n)
{
Sleep((DWORD)n*1000*10);
return ((DWORD)n*10);
}
while(1)
{
}
GetExitCodeThread(hThread2,&exitCode2);
不是没起作用,而是在sleep结束前已经把线程结束了。
你可以这样测试,在CloseHandle(hThread1)前加上slepp,与子线程同样的时间或更长,然后在子线程的return处设断点,你会看到sleep结束后跑到断点处。