程序如下:
#include <stdio.h>
#include <windows.h>DWORD WINAPI HelloFunc(LPVOID arg)
{
int *a ;
a = (int* ) (arg); printf("Helle func!%d\n",*a);
return 0 ;
}void main()
{ int a[1]; LPVOID arg; HANDLE  hThread[4]; for(int index = 0; index < 4; index++)
{
*a = index;
arg = (LPVOID)a; hThread[ index ] = 
CreateThread(NULL,0,HelloFunc,arg,0,NULL);
//Sleep(1);
}

Sleep(20);}
我运行了很多次,为什么输出总是:
Helle func!3
Helle func!3
Helle func!3
Helle func!3

解决方案 »

  1.   

    解决办法是将注释掉的Sleep(1);改为Sleep(0);原因是在
    for(int index = 0; index < 4; index++)
    {
    *a = index;
    arg = (LPVOID)a; hThread[ index ] = 
    CreateThread(NULL,0,HelloFunc,arg,0,NULL);
    //Sleep(1);
    }
    这个循环中没有线程切换,等这个循环结束后,a[0]的值是3,切换到CreateThread的4个线程中的某个时,它打印a[]中的值,当然是3。
      

  2.   

    楼上的解释我不是很清楚,能否再详细些,因为我才开始使用多线程,很多东西还不太清楚!
    另外如果在循环中不注释掉Sleep(1)的话输出是如下的:
    Helle func!0
    Helle func!1
    Helle func!2
    Helle func!3
      

  3.   

    关于多线程编程的知识可能得几大篇文章才能讲完,你可以到网上找这样的书籍看看。如果你希望线程顺序执行,可以改成:
    for(int index = 0; index < 4; index++)
    {
    *a = index;
    arg = (LPVOID)a; hThread[ index ] = 
    CreateThread(NULL,0,HelloFunc,arg,0,NULL);
             WaitForSingleObject(hThread[ index ], -1);
    //Sleep(1);
    }