[英]WaitForMultipleObjects doesnt wait until all threads finish
What I want are 5 threads that print something indefinitely.我想要的是 5 个线程,可以无限期地打印一些东西。 I used the
WaitForMultipleObjects
API to wait until the threads finish and then exit the main.我使用
WaitForMultipleObjects
API 等到线程完成然后退出主线程。 But it seems to exit the main just after starting the thread.但它似乎在启动线程后就退出了主线程。
WaitForSingleObject
seems to work fine when there is a single thread to wait for.当有一个线程等待时,
WaitForSingleObject
似乎工作正常。 I am not sure why I don't get the same behavior when using WaitForMultipleObjects
.我不确定为什么在使用
WaitForMultipleObjects
时没有得到相同的行为。
#include <Windows.h>
#include <stdio.h>
DWORD __stdcall ThreadProc(DWORD * TID) {
//expected this block to run infinitely.
while (1) {
printf("Inside Thread: %d. \n", * TID);
Sleep(1000);
}
return 0;
}
int main() {
DWORD ThreadId;
HANDLE lpHandles[5];
for (int i = 0; i < 5 ; i++) {
HANDLE Threadhandle = CreateThread(0, 0, ThreadProc, &ThreadId, 0, &ThreadId);
printf("Thread %d -> ID %d started. \n", i, ThreadId);
lpHandles[i] = Threadhandle;
}
WaitForMultipleObjects(MAXIMUM_WAIT_OBJECTS, TRUE, lpHandles, INFINITE);
return 0;
}
This is the code you want:这是你想要的代码:
#include <Windows.h>
#include <stdio.h>
DWORD IDs[5];
DWORD __stdcall ThreadProc(DWORD* TID) {
//expected this block to run infinitely.
while (1) {
printf("Inside Thread: %d. \n", *TID);
Sleep(1000);
}
return 0;
}
#define NBOFTHREADS 5
int main() {
HANDLE lpHandles[NBOFTHREADS];
for (int i = 0; i < NBOFTHREADS; i++) {
HANDLE Threadhandle = CreateThread(0, 0, ThreadProc, &IDs[i], 0, &IDs[i]);
printf("Thread %d -> ID %d started. \n", i, IDs[i]);
lpHandles[i] = Threadhandle;
}
WaitForMultipleObjects(NBOFTHREADS, lpHandles,TRUE, INFINITE);
return 0;
}
In your code you pass the pointer to ThreadId
to the thread, but ThreadId
is being overwritten upon the creation of each thread, therefore all threads are displaying the same thread id.在您的代码中,您将指向
ThreadId
的指针传递给线程,但ThreadId
在创建每个线程时被覆盖,因此所有线程都显示相同的线程 ID。
You can simplify the code above by using GetCurrentThreadId
and not care about pasing the thread IDs to the thread.您可以通过使用
GetCurrentThreadId
来简化上面的代码,而不用关心将线程 ID 传递给线程。
DWORD __stdcall ThreadProc(void *unused) {
//expected this block to run infinitely.
while (1) {
printf("Inside Thread: %d. \n", GetCurrentThreadId());
Sleep(1000);
}
return 0;
}
...
HANDLE Threadhandle = CreateThread(0, 0, ThreadProc, NULL, 0, &IDs[i]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.