Windows C++ 线程参数传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5654015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:37:53  来源:igfitidea点击:

Windows C++ Thread Parameter Passing

c++windowsmultithreadingfunction-pointers

提问by rossb83

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

在 Windows C++ 中,以下内容创建了一个线程:

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

This will run "function" in a new thread and pass it "parameter" as a void* or LPVOID.

这将在新线程中运行“函数”并将其“参数”作为 void* 或 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?

假设我想将两个参数传递给“函数”,除了创建包含两个变量的数据结构然后将数据结构转换为 LPVOID 之外,还有更好的方法吗?

回答by JWood

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

不,这是唯一的办法。只需创建一个具有 2 个数据成员的结构并将其作为 void* 传递

回答by Dattatraya Mengudale

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

回答by rerun

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.

这是将参数传递给线程的标准方法,但是您的新线程无法访问进程中的任何内存,因此只要您提供适当的同步控制,就可以将难以传递的内容或大量数据作为共享资源访问.

回答by Tod

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 explanationthat you can refer to if you're interested. In the write-up, where you see OSTaskCreate(), just mentally substitute CreateMethod().

我认为有更好的方法,我一直在嵌入代码中使用它。它实际上源于将成员方法传递给与 CreateThread() 非常相似的函数的愿望。之所以需要,是因为该类已经将线程代码所需的所有参数作为成员数据(带有适当的设置器)。 我写了一个更详细的解释,如果你有兴趣可以参考。在您看到 OSTaskCreate() 的文章中,只需在心里替换 CreateMethod()。