Boost logo

Boost :

Subject: Re: [boost] [threads] Unexpected behaviour of Thread loal storage
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2015-05-06 04:02:26


On Wed, May 6, 2015 at 9:37 AM, Fu ji <fujimailing_at_[hidden]> wrote:
> I try to summing up all things:
>
> I try to export thread local storage (dllexport)
> from firstmodule and import in secondmodule (dllimport) but with no effect.
> In firstmodule I have Includes/ThreadLocalStorage.h with delaration:
>
> #include <boost/thread/tss.hpp>
>
> namespace threads {
>
> extern __declspec(dllexport)
> boost::thread_specific_ptr<int> TlsStorage;
> extern __declspec(dllexport) int
> tls_value_storage = 0;
>
> }
>
> integer tls_value_storage is for testing purpose only. There is also
> Src/ThreadLocalStorage.cpp with:
>
> #include <Include/ThreadLocalStorage.h>
>
>
> namespace threads {
>
> __declspec(dllexport)
> boost::thread_specific_ptr<int> TlsStorage;
> extern __declspec(dllexport) int
> tls_value_storage;

extern is not needed here, unless you want to define tls_value_storage
elsewhere.

> }
>
> and the last one: in stdafx.h in secondmodule module:
>
> namespace threads {
>
> extern __declspec(dllimport)
> boost::thread_specific_ptr<int> TlsStorage;
> extern __declspec(dllimport) int
> tls_value_storage2;
> }
>
> But after all when I try to change set tls in secondmodule
>
>
> threads::TlsStorage.reset(&new_language_value);
> int *sanity_check = threads::TlxStorage.get(); //.get()
> return proper value
>
>
> Funtion();
>
> Now we go to the firstmodule, function() (using the same thread)
>
> int sanity_check_1 = threads::tls_value_storage; //Proper
> value
> int *sanity_check_2 = threads::TlsStorage.get(); //
> Something bad happens, return uninitialized tls

Do you link to Boost.Thread built as a shared library (dll)? Both
libraries must use Boost.Thread dll because it maintains a global list
of thread_specific_ptr storage objects internally.

> I think it can be fault of missing extern before __declspec(dllexport)
> boost::thread_specific_ptr<int> TlsStorage
> in ThreadLoalStorage.cpp but when I add "extern" I have:
>
> error LNK2001: unresolved external symbol "__declspec(dllimport) class
> boost::thread_specific_ptr<int> threads::TlsStorage"
> (__imp_?TlsStorage_at_threads@tlx@@3V?$thread_specific_ptr_at_H@boost@@A)
>
> in compiling process. Maybe it's some issue with mangling ?

When you write extern you declare the object which must be defined
elsewhere. There must be exactly one definition of the object (without
extern), so you would typically declare it in a header (for reuse by
other source files) and define in a cpp file. The error says that you
provided no definition of the TlsStorage object (because you added the
extern keyword, changing the definition into a declaration).


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk