开发者

Windows C++ Thread Parameter Passing

开发者 https://www.devze.com 2023-02-24 05:12 出处:网络
In Windows c++, the following creates a thread: CreateThread(NULL, NULL, function, parameter, NULL, &threadID);

In Windows c++, the following creates a thread:

CreateThread(NULL, NULL, function, parameter, NULL, &threadID);

This w开发者_Go百科ill 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?


No, that's the only way. Just create a struct with the 2 data members and pass that as void*


#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;
}


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.


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().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号