使用具有 ThreadStatic 属性的并行扩展。会不会泄漏内存?

发布于 2024-09-05 00:57:43 字数 350 浏览 10 评论 0原文

我相当频繁地使用并行扩展,而且我刚刚遇到了一种情况,使用线程本地存储可能是明智的,允许工作线程重用对象。因此,我正在查看 ThreadStatic 属性,该属性将静态字段/变量标记为每个线程具有唯一值。

在我看来,在没有任何 PE 线程重用保证的情况下,将 PE 与 ThreadStatic 属性一起使用是不明智的。也就是说,如果在某种程度上创建和销毁线程,变量(以及它们指向的对象)是否会在线程本地存储中保留一段不确定的时间,从而导致内存泄漏?或者线程存储可能与线程绑定并在线程被处置时被处置?但是,池中仍然可能存在长期存在的线程,并且从线程所使用的各种代码片段中积累线程本地存储。

有没有更好的方法通过PE获取线程本地存储?

谢谢。

I'm using Parallel Extensions fairly heavily and I've just now encountered a case where using thread local storage might be sensible to allow re-use of objects by worker threads. As such I was looking at the ThreadStatic attribute which marks a static field/variable as having a unique value per thread.

It seems to me that it would be unwise to use PE with the ThreadStatic attribute without any guarantee of thread re-use by PE. That is, if threads are created and destroyed to some degree would the variables (and thus objects they point to) remain in thread local storage for some indeterminate amount of time, thus causing a memory leak? Or perhaps the thread storage is tied to the threads and disposed of when the threads are disposed? But then you still potentially have threads in a pool that are longed lived and that accumulate thread local storage from various pieces of code the threads are used for.

Is there a better approach to obtaining thread local storage with PE?

Thankyou.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

じее 2024-09-12 00:57:43

我强烈鼓励使用线程本地存储的正常模式,如这篇 MSDN 文章中所述

当您使用 [ThreadStatic] 时,重要的是线程池线程在终止时是否清除 TLS 变量。 MSDN 文档中没有任何建议表明它不存在。实现起来并不难,只需要调用 TlsFree() API 函数即可。我写了一个小测试应用程序,没有任何泄漏的证据。

I would strongly encourage using the normal pattern for thread-local storage, described in this MSDN article.

When you use [ThreadStatic], what matters is whether or not a threadpool thread cleans up the TLS variables when it terminates. There isn't any suggestion in the MSDN docs that it doesn't. It wouldn't be hard to implement, it only has to call the TlsFree() API function. I wrote a little test app, no evidence of any leak.

很快妥协 2024-09-12 00:57:43

编辑:鉴于汉斯的回答,听起来 TLS 实际上无论如何都会被清理...这只是留下了一点答案:

你真的没有更好的方法在线程中重用值吗?如果有两个任务使用同一线程(一个完成,然后另一个运行),它们真的需要相同的值吗?您是否实际上只是使用它来避免在任务中以更受控的方式传播数据?

EDIT: Given Hans's answer, it sounds like the TLS actually would be cleaned up anyway... which just leaves this bit of the answer:

Do you really have no better way of reusing values within a thread? If there are two tasks which use the same thread (one completes, then the other runs) are they really going to want the same value? Are you actually just using this as a way of avoiding propagating the data in a more controlled way through your task?

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