You are currently browsing the archives for the Visual C++ Express category


Creating threads

I struggled with this concept for a while so thought I would write a little post about it.

Is it possible to create a multi-threaded application in Visual C++ Express, which lacks ATL and MFC library support.

The answer is yes, you use the CreateThread API call and here’s how:

Make sure these headers are included:

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

Now create your thread function, this function is what gets executed by the CreateThread API call. In my example I want to pass an object to the thread and then do something with it. In my case I am invoking my objects load function.

DWORD WINAPI LoadObject(LPVOID lpParameter){
	MyObjectType* f;
	f = (MyObjectType *) lpParameter;
	f->load();
	return 0;
}

Now we’re ready to create our thread from within our main code…

DWORD dwThreadId;

HANDLE hThread = CreateThread(
	NULL,          // pointer to security attributes
	0,             // initial thread stack size
	LoadObject, // pointer to thread function
	(LPVOID)&f, // argument for new thread
	0,          // creation flags (immediate)
	&dwThreadId // pointer to receive thread ID
);

if (NULL == hThread) {
	// error reporting here
	exit(1);
}

// for example purposes, wait for the thread to complete and each second until it does print a '.' to the console.

while(TRUE) {
	if (WaitForSingleObject(hThread, 1000)==WAIT_OBJECT_0) break;
	printf(".");
}

// You then need to close your handle to the thread with

CloseHandle(hThread);

// That's it, obviously a very simple example and you will want to be creating multiple threads simultaniously etc.