开发者

Using Parallel Extensions with ThreadStatic attribute. Could it leak memory?

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 threa开发者_如何学编程d 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.


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜