线程池局部变量概念

发布于 2024-12-05 22:37:02 字数 290 浏览 1 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

世界如花海般美丽 2024-12-12 22:37:02

在多个线程中调用单个函数是否会在各个线程中生成变量的本地副本?

嗯,这并不是说它制作了变量的本地副本。每个局部变量/线程对都是一个特定的存储位置,并且该存储位置与任何其他局部变量/线程对都不相同。

我已经产生了等于系统中处理器(核心)数量的线程,然后在线程之间划分任务以在各个行上进行处理。

你为什么要自己这么做?使用TPL

Does calling a single function in multiple threads make local copies of the variables in individual threads??

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.

I have spawned out threads equal to no of processors(cores) in the system and then dividing the task between the threads to process on the individual rows.

Why are you doing this yourself? Use the TPL.

jJeQQOZ5 2024-12-12 22:37:02

我认为您应该重新考虑解决方案并尝试使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文