Originally Posted by
valaris
Heya
I was attempting to create a thread inside of a class as so:
Code:
SomeClass::DoWork()
{
::AfxBeginThread(ThreadProc, NULL);
}
UINT SomeClass::ThreadProc(LPVOID pArg)
{
//work...
return TRUE;
}
also I tried to
Code:
SomeClass Instance;
::AfxBeginThread(&Instance.ThreadProc, NULL);
Basically I'm wondering is it possible in C++ to create a thread inside your object, or create a thread running an objects method? In C# this is no problem, I just cant seem to find any examples of doing this in C++ without making a seperate function outside of a class, or making the class's method static.
Thanks for any info.
The reason is that CreateThread is C, and not C++. AfxBeginThread merely wraps CreateThread, and thus also has a C interface.
In short, you can blame Microsoft's C compatibility for the lack of this functionality.
The problem is that these functions really should take an extra argument - the "this" pointer, as explained. That is because there are several instances of a class, so which instance's function should be called?
However, I made a quick solution that I hope works.
A C++ variant of CreateThread:
Code:
#include <windows.h>
#include <iostream>
template<typename ParamType, typename ClassType, typename ReturnType> struct ThreadParams
{
ParamType* Param;
ClassType* Instance;
ReturnType (ClassType::* Function)(ParamType* Param);
HANDLE hProcess;
};
template<typename ParamType, typename ClassType, typename ReturnType> DWORD WINAPI ThreadFnc(void* pParam)
{
ThreadParams<ParamType, ClassType, ReturnType>* pParams = (ThreadParams<ParamType, ClassType, ReturnType>*)pParam;
(pParams->Instance->*pParams->Function)(pParams->Param);
CloseHandle(pParams->hProcess);
delete pParams;
return 0;
}
template<typename ParamType, typename ClassType, typename ReturnType> DWORD CPPCreateThread(ReturnType (ClassType::* Function)(ParamType* Param), ClassType* Instance, ParamType* Param)
{
ThreadParams<ParamType, ClassType, ReturnType>* pParams = new ThreadParams<ParamType, ClassType, ReturnType>;
pParams->Param = Param;
pParams->Instance = Instance;
pParams->Function = Function;
HANDLE hProcess = CreateThread(NULL, NULL, &ThreadFnc<ParamType, ClassType, ReturnType>, pParams, CREATE_SUSPENDED, NULL);
if (hProcess == NULL)
return GetLastError();
pParams->hProcess = hProcess;
ResumeThread(hProcess);
DWORD dwErr = GetLastError();
if (dwErr != ERROR_SUCCESS)
{
CloseHandle(hProcess);
delete pParams;
}
return dwErr;
}
class foo
{
public:
foo() { CPPCreateThread<void>(&foo::ThreadFunc, this, NULL); }
void ThreadFunc(void*) { std::cout << "Hi! This is inside the thread!"; };
};
int main() { foo f; Sleep(1000); }