Win32 C++ multithreading question.

Miscellaneous Forums/General Discussion/Win32 C++ multithreading question.

I'm trying to create a multi-threaded DLL/Exe in native Win32 API. I am new to threading in Win32 (done in .NET). What I do not know is how to "return" to the main thread using event style functionality. i.e.


#include <windows.h>
#include <stdio.h>
#include <time.h>

DWORD WINAPI MyThread(LPVOID);

int main(void)
{
	DWORD iID[2];
	HANDLE hThreads[2];
	DWORD waiter;
	
	srand((unsigned)time(NULL));
	hThreads[0] = CreateThread(NULL, 0, MyThread, "T1", NULL, &iID[0]);
	hThreads[1] = CreateThread(NULL, 0, MyThread, "T2", NULL, &iID[1]);


	waiter = WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);
	return 0;
}

DWORD WINAPI MyThread(LPVOID n)
{
	char *name = (char *)n;
	for(int i=0; i<10; i++)
	{
		printf("Thread %s: i=%d\n", name, i);
		if ("T1" == name)
			SleepEx(100, false);
		else
			SleepEx(200, false);
	}
	return 0;
}



So after MyThread() finishes, how do I call a function on the parent thread that will then do its appropriate functionality. Such as "int FinishedLoading(void)"

Welcome to a world of pain.

Seriously, there's a few things you can do. You can have a global usage counter which increments as threads are launched, and decremented as threads are closed. That makes your main code either sit there busy-looping or off doing something else, checking occasionally. Or you can use mutexes.

Either works.

A trick I've done in the past is set up a structure containing some data and hand it to the new thread. It's a bit of a trick, from memory, but nothing I can't dig out. One of the parameters I'd pass in was the HWND of the window that was launching the threads. I'd keep a count of how many threads I had launched, and each thread would post a message (WM_USER+x) back to the HWND. I'd trap the message and decrement the launch counter.

One (annoying) thing I found was there seems to be a hard-coded limit on the number of threads a process can have: 2000. It's a problem for me because I was, err, port-scanning a network at the time, and my code launched a thread for every IP address, then launched a thread for every port (for every IP address). I needed some code to sit there and check if the thread was actually created. If it wasn't, I would delay 100ms and try again, until all my threads were launched.

Neil

Look on MSDN for WaitForSingleObject, you could call this periodically to test if the thread is still executing. Or whack a message across the system using WM_USER (as above) or employ a Mutex.

From the looks of it, WaitForSingleObject seems what I need with a 1ms timeout.

Man, its so much work coming from Blitz, or .NET programming, and getting into C++... bare C++...

But I LOVE IT!

Anyone know of a good C++ related forums that is pretty active and knowledgeable?

I don't visit C++ forums but there is a shed load of good examples over at http://www.codeproject.com/