线程池局部变量概念
我正在尝试使用 C# 中的 ThreadPool 来对我的应用程序进行多线程处理。我有一个 3D 数组,必须单独处理每一行。我已经产生了等于系统中处理器(核心)数量的线程,然后在线程之间划分任务以在各个行上进行处理。
为所有线程调用一个函数,在这些线程中我使用线程在不同线程之间划分数据。 (类似 SIMD 的东西)。该函数还调用其他小函数。这些函数还创建动态分配的数组作为中间值的临时存储空间。我想知道线程中局部变量的概念是什么。在多个线程中调用单个函数是否会在各个线程中生成变量的本地副本?我该如何设计这样的代码?
请解释一下..
I am trying to multi thread my application using ThreadPool
in c#. I have a 3D array in which I have to process for every row separately. I have spawned out threads equal to number of processors(cores) in the system and then dividing the task between the threads to process on the individual rows.
A single function is called for all the threads in which I am using the thread to divide the data between different threads. (Kind of SIMD thing). The function calls other small functions as well. Also the functions create dynamically allocated arrays as a temporary storage space for intermediate values. I want to know what is the concept of local variables in threads. Does calling a single function in multiple threads make local copies of the variables in individual threads? How do I go about designing such a code?
Please explain..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,这并不是说它制作了变量的本地副本。每个局部变量/线程对都是一个特定的存储位置,并且该存储位置与任何其他局部变量/线程对都不相同。
你为什么要自己这么做?使用TPL。
Well, it's not that it makes local copies of the variables. Every local variable / thread pair is a specific storage location, and that storage location is not the same for any other local variable / thread pair.
Why are you doing this yourself? Use the TPL.
我认为您应该重新考虑解决方案并尝试使用 Parallel.For 作为您的解决方案。
MSDN Parallel.For
但要回答您的问题是,如果设计为线程安全,您可以在多个线程中使用单个函数。您可以在函数中使用局部变量,因为它们是函数的局部变量,并且每次调用都会获得一个单独的内存位置。
I think you should rethink the solution and try to use Parallel.For for your solution.
MSDN Parallel.For
But to answer your question you can use a single function in multiple threads if it is designed to be thread safe. And you can use local variables in your functions because they are local to the function and every call will get a separate memory location.