Reputation: 81
Summarised question: What is the best method to monitor thread variables in a function external to thread?
Original Question: I am looking to get a better understanding of the best practices when using Windows threading. I understand there are more modern methods for threading but I am restricted to using CreateThread. The current setup contains a WaitForSingleObject function inside the function called by CreateThread that updates some pointers. I need to access these pointers externally to the thread. What is the best practices to access data within the WaitForSingleObject function? Passing parameters into the function is straightforward using the LPVOID params argument, but there doesn't seem to be an output option other than the thread ID and using globals.
HANDLE WINAPI CreateThread( __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, __in SIZE_T dwStackSize, __in LPTHREAD_START_ROUTINE lpStartAddress, __in_opt LPVOID lpParameter, __in DWORD dwCreationFlags, __out_opt LPDWORD lpThreadId );
Upvotes: 0
Views: 509
Reputation: 81
Thanks to Adrian for the advice. Passing a pointer to a structure worked. A simplified version of the working code is below.
#include <Windows.h>
#include <iostream>
struct MyStruct {
int var;
};
DWORD WINAPI mythread(LPVOID lpParameter)
{
MyStruct *PSTRUCT = (MyStruct*)lpParameter;
PSTRUCT->var = 22;
std::cout << "Thread function value: " << PSTRUCT->var << std::endl;
return 0;
}
int main(int argc, char* argv[])
{
MyStruct *PSTRUCT;
HANDLE myhandle;
DWORD mythreadid;
PSTRUCT = reinterpret_cast<MyStruct*>(HeapAlloc(GetProcessHeap(), 0, sizeof(MyStruct)));
PSTRUCT->var = 0;
myhandle = CreateThread(0, 0, mythread, (LPVOID)PSTRUCT, 0, &mythreadid);
WaitForSingleObject(myhandle, INFINITE);
std::cout << "Main function value: " << PSTRUCT->var << std::endl;
getchar();
return 0;
}
Upvotes: 0