Reputation: 1762
In Windows c++, the following creates a thread:
CreateThread(NULL, NULL, function, parameter, NULL, &threadID);
This will run "function" in a new thread and pass it "parameter" as a void* or LPVOID.
Suppose I want to pass two parameters into "function", is there a better looking way of doing it besides creating a data structure that contains two variables and then casting the data structure as an LPVOID?
Upvotes: 9
Views: 12023
Reputation: 336
#include <windows.h>
#include <stdio.h>
struct PARAMETERS
{
int i;
int j;
};
DWORD WINAPI SummationThread(void* param)
{
PARAMETERS* params = (PARAMETERS*)param;
printf("Sum of parameters: i + j = \n", params->i + params->j);
return 0;
}
int main()
{
PARAMETERS params;
params.i = 1;
params.j = 1;
HANDLE thdHandle = CreateThread(NULL, 0, SummationThread, ¶ms, 0, NULL);
WaitForSingleObject(thdHandle, INFINITE);
return 0;
}
Upvotes: 6
Reputation: 8242
I think there is a much better way, and I use it all the time in my embedded code. It actually grew out of the desire to pass a member method to a function that is very similar to CreateThread(). The reason that was desired was because the class already had as member data (with appropriate setters) all the parameters the thread code needed. I wrote up a more detailed explanation that you can refer to if you're interested. In the write-up, where you see OSTaskCreate(), just mentally substitute CreateMethod().
Upvotes: 0
Reputation: 25505
That is the standard way to pass a parameter to the thread however your new thread cann access any memory in the process so something that is difficult to pass or a lot of data can be accessed as a shared resource as long as you provide appropriate synchronization control.
Upvotes: 0
Reputation: 2834
No, that's the only way. Just create a struct with the 2 data members and pass that as void*
Upvotes: 16