TransWikia.com

WaitForMultipleObjects doesnt wait until all threads finish

Stack Overflow Asked on November 20, 2021

What I want are 5 threads that print something indefinitely. I used the WaitForMultipleObjects API to wait until the threads finish and then exit the main. 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. I am not sure why I don’t get the same behavior when using 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;

}

One Answer

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.

You can simplify the code above by using GetCurrentThreadId and not care about pasing the thread IDs to the thread.

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]);

Answered by Jabberwocky on November 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP