程序执行很快就结束了。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);
}

解决方案 »

  1.   

    Sleep()是在线程中,主线程结束就没作用了啊
      

  2.   

    你放到main里试试,估计效果就出来了
      

  3.   

    主线程里是
    while(1)  
    {
    }
      

  4.   

    GetExitCodeThread(hThread1,&exitCode1);
    GetExitCodeThread(hThread2,&exitCode2);
      

  5.   

    sorry,那修改Sleep((DWORD)n*1000*10);为一个直接的大时间,看效果。怎么会没有作用,这里sleep()后,os会做线程切换,也就是挂起了你的ThreadFunc线程,转到while(1)执行
      

  6.   

    子线程sleep,当然主线程会run了,然后就closhandle,结束子线程了,跑这几条语句不用很长时间把。
    不是没起作用,而是在sleep结束前已经把线程结束了。
    你可以这样测试,在CloseHandle(hThread1)前加上slepp,与子线程同样的时间或更长,然后在子线程的return处设断点,你会看到sleep结束后跑到断点处。
      

  7.   

    主线程里while(1),是直接break出来了了,没有死循环。