程序如下:
#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
#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
解决方案 »
- 找不到.dll 是什么原因呢?
- 测试隐式转换,麻烦达人看看这错误咋改(编译不过)
- 在VC++ 6中如何让控制台程序结束后暂停?
- 怎么样实现数值转换为STRING是最简单的方法
- 紧急~~与WEB无关,却关乎所有中国人!!
- 本人做了一个JPEG2000开发包,欢迎下载使用
- 端口、套接字
- 还是模板函数的问题
- 关于“hook和如何得到handle”的资料和专门书籍好象很少,希望了解的同志可以share一下自己的心得和相关知识
- 请问,如何打开 '.rar' 文件?
- !!!~~~~~~对话框IDOK,IDCANCEL问题!!
- bind (SOCKET s, const struct sockaddr FAR *addr, int namelen)
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。
另外如果在循环中不注释掉Sleep(1)的话输出是如下的:
Helle func!0
Helle func!1
Helle func!2
Helle func!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);
}