我需要创建 10 个线程并打印出打印线程的 threadId。
#include <windows.h>
#include <stdio.h>
DWORD WINAPI xprint(LPVOID Param)
{
DWORD tID = GetCurrentThreadId();
int count = *(int*)Param + 1;
fprintf(stderr, "Thread Number:%d ThreadID:%d\n", count, tID);
return 0;
}
int main ()
{
DWORD ThreadID[10];
HANDLE ThreadHandle[10];
int i;
for(i=0; i<10; i++){
ThreadHandle[i] = CreateThread(
NULL,
0,
xprint,
&i,
0,
&ThreadID[i]);
if (ThreadHandle[i] == NULL) {
fprintf(stderr,"Can't create thread!\n");
return -1;
}
}
for (i=0; i<10; i++){
WaitForSingleObject(ThreadHandle[i],INFINITE);
CloseHandle(ThreadHandle[i]);
}
}
输出:
Thread Number:1 ThreadID:4952
Thread Number:1 ThreadID:5284
Thread Number:1 ThreadID:5084
Thread Number:1 ThreadID:5656
Thread Number:1 ThreadID:5292
Thread Number:1 ThreadID:3072
Thread Number:1 ThreadID:5904
Thread Number:1 ThreadID:3620
Thread Number:1 ThreadID:6056
Thread Number:1 ThreadID:5676
我不知道我哪里做错了。我想要的输出应该是这样的。
输出:
Thread Number:10 ThreadID:4952
Thread Number:8 ThreadID:5284
Thread Number:3 ThreadID:5084
Thread Number:9 ThreadID:5656
Thread Number:1 ThreadID:5292
Thread Number:2 ThreadID:3072
Thread Number:5 ThreadID:5904
Thread Number:6 ThreadID:3620
Thread Number:4 ThreadID:6056
Thread Number:7 ThreadID:5676
线程号应该是*乱序的。
*发布此问题后,我又运行了几次程序输出:
Thread Number:2 ThreadID:4500
Thread Number:7 ThreadID:5740
Thread Number:7 ThreadID:3772
Thread Number:1 ThreadID:4732
Thread Number:2 ThreadID:4252
Thread Number:2 ThreadID:4264
Thread Number:2 ThreadID:5544
Thread Number:2 ThreadID:4116
Thread Number:2 ThreadID:5240
Thread Number:2 ThreadID:4804
似乎线程号是随机的。但无论如何,相同的数字不应出现两次。