Windows C++线程参数传递
在 Windows c++ 中,以下代码创建一个线程:
CreateThread(NULL, NULL, function, parameter, NULL, &threadID);
这将在新线程中运行“函数”,并将“参数”作为 void* 或 LPVOID 传递给它。
假设我想将两个参数传递给“函数”,除了创建包含两个变量的数据结构然后将数据结构转换为 LPVOID 之外,还有更好看的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,这是唯一的办法。只需创建一个包含 2 个数据成员的结构并将其作为 void* 传递
No, that's the only way. Just create a struct with the 2 data members and pass that as void*
这是将参数传递给线程的标准方法,但是您的新线程可以访问进程中的任何内存,因此只要您提供适当的同步控制,就可以将难以传递的内容或大量数据作为共享资源进行访问。
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.
我认为有一种更好的方法,并且我一直在嵌入式代码中使用它。它实际上源于将成员方法传递给与 CreateThread() 非常相似的函数的愿望。之所以需要这样做,是因为该类已经具有线程代码所需的所有参数作为成员数据(具有适当的设置器)。 我写了一个更详细的解释,您可以有兴趣的话可以参考一下。在文章中,当您看到 OSTaskCreate() 时,只需在心里替换 CreateMethod() 即可。
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().