Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

__declspec(thread) with DLL

93 views
Skip to first unread message

Emmanuel Stapf [ES]

unread,
Feb 9, 2007, 1:23:20 PM2/9/07
to
Hi,

I've build a .lib file that uses the __declspec(thread) qualifier on some global
variables. When I use this .lib file in an EXE, it works fine. But if used in a
DLL, each time I access those global variables I get a segmentation violation.
Is there a workaround to make it work in a DLL?

Thanks,
Manu

Igor Tandetnik

unread,
Feb 9, 2007, 2:05:27 PM2/9/07
to

__declspec(thread) doesn't work in a DLL loaded dynamically with
LoadLibrary (such as, for example, a COM DLL). The only way around is to
drop __declspec(thread) and use thread-local strorage APIs (TlsAlloc et
al) directly.
--
With best wishes,
Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925


Alex Blekhman

unread,
Feb 9, 2007, 2:26:01 PM2/9/07
to

Yes, there is a workaround. Use TlsXXX functions explicitly
instead of `__declspec(thread)'. `__declspec(thread)'
qualifier doesn't work well when DLL is loaded with call to
`LoadLibrary'. Here's quote from MSDN:

"Rules and Limitations for TLS"
http://msdn2.microsoft.com/en-us/library/2s9wt68x(VS.80).aspx

<quote>
If a DLL declares any nonlocal data or object as
__declspec( thread ), it can cause a protection fault if
dynamically loaded. After the DLL is loaded with
LoadLibrary, it causes system failure whenever the code
references the nonlocal __declspec( thread ) data.
</quote>

Here's the explanation how to use TLS in DLL's:

"Using Thread Local Storage in a Dynamic-Link Library"
http://msdn2.microsoft.com/en-us/ms686997.aspx

Alex

Emmanuel Stapf [ES]

unread,
Feb 10, 2007, 12:27:06 PM2/10/07
to
Alex Blekhman wrote:
> "Using Thread Local Storage in a Dynamic-Link Library"
> http://msdn2.microsoft.com/en-us/ms686997.aspx

Thanks, this does work indeed.

Regards,
Manu

0 new messages