我创建了 4 个线程,但是当我执行这个程序时,我得到这个作为输出:
Thread #: 1
Thread #: 2
Thread #: 3
Thread #: 3
Thread #: 4
Thread #: 4
Thread #: 4
Thread #: 5
Thread #: 5
Thread #: 5
.
.
.
Thread #: 5
Thread #: 5
我有两个问题:
- 我只创建了 4 个线程,为什么它显示线程 #: 5
- 创建的所有 4 个线程都应该按顺序运行,但为什么它只运行最后一个创建的线程?
源代码:
#include<windows.h>
HANDLE ThreadHandle[4];
DWORD dwThreadId[4];
DWORD WINAPI ThreadFunction(LPVOID param)
{
while (1)
{
printf("Thread #: %d\n", *((int*)param));
}
Sleep(10);
return 0;
}
int main()
{
static int i = 0;
for (i = 1; i <= 4; i++)
{
ThreadHandle[i] = CreateThread(NULL, 0, ThreadFunction, (LPVOID)&i, 0, &dwThreadId[i]);
Sleep(10);
}
while (1)
{
Sleep(100);
}
return 0;
}