Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows C++ Thread Parameter Passing

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?

like image 496
rossb83 Avatar asked Apr 13 '11 18:04

rossb83


1 Answers

#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, &params, 0, NULL);
    WaitForSingleObject(thdHandle, INFINITE);

    return 0;
}
like image 163
Dattatraya Mengudale Avatar answered Oct 16 '22 04:10

Dattatraya Mengudale