使用并行扩展与ThreadStatic属性。难道是内存泄漏?属性、内存、ThreadStatic

2023-09-03 07:15:01 作者:夜巷

我使用的是并行扩展相当严重和我刚才碰到的地方使用线程本地存储可能是明智的,允许重复使用对象由工作线程的情况。因此我一直在寻找这标志着一个静态字段/变量具有每个线程的唯一值的ThreadStatic属性。

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.

在我看来,这将是不明智的使用PE与ThreadStatic属性无螺纹再使用通过PE任何保证。也就是说,如果被创建和销毁,以某种程度的线程将(它们指向,从而对象)的变量保持在线程局部存储器一段不确定的时间,因此引起了内存泄漏?或者线程存贮是联系在一起的螺纹和设置在线程布置的?但你仍然有可能在池中的线​​程所渴望居住,并且从各个部分$ C $的积累线程本地存储c中的线程用途。

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.

有没有更好的方法来获得线程本地存储与PE?

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

三江源。

推荐答案

我会强烈建议使用线程本地存储的正常模式,在此描述的 MSDN文章。

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

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

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.