Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread local storage with __declspec(thread) fails in C++/CLI

I'm working on a project where we mix .NET code and native C++ code via a C++/CLI layer. In this solution I want to use Thread Local Storage via the __declspec(thread) declaration:

__declspec(thread) int lastId = 0;

However, at the first access of the variable, I get a NullReferenceException. To be more precise, the declaration is done within a ref class (a .NET class implemented in C++/CLI).

I have already read something about __declspec(thread) does not work with delay loaded DLLs. Am I using delay loaded DLLs automatically if I use .NET?

like image 662
EFrank Avatar asked Oct 22 '08 07:10

EFrank


2 Answers

It seems that __declspec(thread) isn't supported by CLR.

Take in mind that .net threads aren't necesarily native threads, but can be also fibers, so standard API's for threads don't work on them.

If you have a managed class, then you should use managed threading API's for thread local storage.

There are a lot of articles regarding this difference. This is just to get you started.

As a tip: You could use the ThreadStatic Attribute instead of the TLS in order to improve performance. In case you are working with ASP.NET applications, you need to remember some things about TLS.

like image 175
Bogdan Maxim Avatar answered Nov 15 '22 00:11

Bogdan Maxim


Unfortunately not supported. Here's a blog entry with a workaround:

http://blogs.msdn.com/jeremykuhne/archive/2006/04/19/578670.aspx

like image 34
Bruce Avatar answered Nov 14 '22 22:11

Bruce