// Listing 1 - thread1.h
#include <winbase.h> // for CreateThread and macros
namespace MSVC
{
// works in MSVC 6 but has portability problems - use with risk
template <typename Object>
void runInThread(
Object& objectInstance,
DWORD (WINAPI Object::*memberFunc)(void),
HANDLE* handle=0,
DWORD* id=0)
{
using std::runtime_error;
DWORD (WINAPI *threadFunc)(void*);
// pass object "this" pointer via thread void* argument
void *thisPointer = static_cast<void*>(&objectInstance);
// copy class member pointer to global function pointer
*reinterpret_cast<long*>(&threadFunc) =
*reinterpret_cast<long*>(&memberFunc);
DWORD threadId = -1;
// replace CreateThread if your compiler has a function
// to initialize a thread-safe C runtime library
HANDLE result =
CreateThread(
0,
0,
threadFunc,
thisPointer,
0,
&threadId);
if (result==0) throw runtime_error("CreateThread failed");
if (handle) *handle = result;
if (id) *id = threadId;
}
}