Merged branch 'master' of https://github.com/Nemo1369/libcds
[libcds.git] / cds / threading / details / _common.h
1 /*
2     This file is a part of libcds - Concurrent Data Structures library
3
4     (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2017
5
6     Source code repo: http://github.com/khizmax/libcds/
7     Download: http://sourceforge.net/projects/libcds/files/
8
9     Redistribution and use in source and binary forms, with or without
10     modification, are permitted provided that the following conditions are met:
11
12     * Redistributions of source code must retain the above copyright notice, this
13       list of conditions and the following disclaimer.
14
15     * Redistributions in binary form must reproduce the above copyright notice,
16       this list of conditions and the following disclaimer in the documentation
17       and/or other materials provided with the distribution.
18
19     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20     AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21     IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23     FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24     DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25     SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26     CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27     OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28     OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #ifndef CDSLIB_THREADING__COMMON_H
32 #define CDSLIB_THREADING__COMMON_H
33
34 #include <cds/urcu/details/gp_decl.h>
35 #include <cds/urcu/details/sh_decl.h>
36 #include <cds/algo/elimination_tls.h>
37
38 namespace cds {
39     /// Threading support
40     /** \anchor cds_threading
41         The \p CDS library requires support from the threads.
42         Each garbage collector manages a control structure on the per-thread basis.
43         The library does not dictate any thread model. To embed the library to your application you should choose
44         appropriate implementation of \p cds::threading::Manager interface
45         or should provide yourself.
46         The \p %cds::threading::Manager interface manages \p cds::threading::ThreadData structure that contains GC's thread specific data.
47
48         Any \p cds::threading::Manager implementation is a singleton and it must be accessible from any thread and from any point of
49         your application. Note that you should not mix different implementation of the \p cds::threading::Manager in your application.
50
51         Before compiling of your application you may define one of \p CDS_THREADING_xxx macro in cds/user_setup/threading.h file:
52             - \p CDS_THREADING_AUTODETECT - auto-detect appropriate threading model for your platform and compiler. This is
53                 predefined value of threading model in <tt>cds/user_setup/threading.h</tt>.
54             - \p CDS_THREADING_WIN_TLS - use <tt>cds::threading::wintls::Manager</tt> implementation based on Windows TLS API.
55                 Intended for Windows and Microsoft Visual C++ only. This is default threading model for Windows and MS Visual C++.
56             - \p CDS_THREADING_MSVC - use <tt>cds::threading::msvc::Manager</tt> implementation based on Microsoft Visual C++ <tt>__declspec(thread)</tt>
57                 declaration. Intended for Windows and Microsoft Visual C++ only.
58                 This macro should be explicitly specified if you want to use <tt>__declspec(thread)</tt> keyword.
59             - \p CDS_THREADING_PTHREAD - use <tt>cds::threading::pthread::Manager</tt> implementation based on pthread thread-specific
60                 data functions \p pthread_getspecific / \p pthread_setspecific. Intended for GCC and clang compilers.
61                 This is default threading model for GCC and clang.
62             - \p CDS_THREADING_GCC - use <tt>cds::threading::gcc::Manager</tt> implementation based on GCC \p __thread
63                 keyword. Intended for GCC compiler only. Note, that GCC compiler supports \p __thread keyword properly
64                 not for all platforms and even not for all GCC version.
65                 This macro should be explicitly specified if you want to use \p __thread keyword.
66             - \p CDS_THREADING_CXX11 - use <tt>cds::threading::cxx11::Manager</tt> implementation based on \p thread_local
67                 keyword introduced in C++11 standard. May be used only if your compiler supports C++11 thread-local storage.
68             - \p CDS_THREADING_USER_DEFINED - use user-provided threading model.
69
70         These macros select appropriate implementation of \p cds::threading::Manager class. The child namespaces of cds::threading
71         provide suitable implementation and import it to cds::threading by using \p using directive (or by using inline namespace if the compiler
72         supports it). So, if you need to call threading manager functions directly you should refer to \p cds::threading::Manager class.
73
74         @note Usually, you should not use \p cds::threading::Manager instance directly.
75         You may specify \p CDS_THREADING_xxx macro when building, everything else will setup automatically when you initialize the library,
76         see \ref cds_how_to_use "How to use libcds".
77
78         The interface of \p cds::threading::Manager class is the following:
79         \code
80         class Manager {
81         public:
82             // Initialize manager (called by cds::Initialize())
83             static void init();
84
85             // Terminate manager (called by cds::Terminate())
86             static void fini();
87
88             // Checks whether current thread is attached to \p libcds feature or not.
89             static bool isThreadAttached();
90
91             // This method must be called in beginning of thread execution
92             // (called by ctor of GC thread object, for example, by ctor of cds::gc::HP::thread_gc)
93             static void attachThread();
94
95             // This method must be called in end of thread execution
96             // (called by dtor of GC thread object, for example, by dtor of cds::gc::HP::thread_gc)
97             static void detachThread();
98
99             // Get cds::gc::DHP thread GC implementation for current thread;
100             static gc::DHP::thread_gc_impl&   getDHPGC();
101         };
102         \endcode
103
104         The library's core (dynamic linked library) is free of usage of user-supplied \p cds::threading::Manager code.
105         \p cds::threading::Manager is necessary for header-only part of \p CDS library (for \ref cds::threading::getGC functions).
106
107
108         Each thread that uses \p libcds data structures should be attached to threading::Manager before using
109         lock-free data structs.
110         See \ref cds_how_to_use "How to use" section for details
111
112         <b>Note for Windows</b>
113
114         When you use Garbage Collectors (GC) provided by \p libcds in your dll that dynamically loaded by \p LoadLibrary then there is no way
115         to use \p __declspec(thread) declaration to support threading model for \p libcds. MSDN says:
116
117         \li If a DLL declares any nonlocal data or object as __declspec( thread ), it can cause a protection fault if dynamically loaded.
118             After the DLL is loaded with \p LoadLibrary, it causes system failure whenever the code references the nonlocal __declspec( thread ) data.
119             Because the global variable space for a thread is allocated at run time, the size of this space is based on a calculation of the requirements
120             of the application plus the requirements of all the DLLs that are statically linked. When you use \p LoadLibrary, there is no way to extend
121             this space to allow for the thread local variables declared with __declspec( thread ). Use the TLS APIs, such as TlsAlloc, in your
122             DLL to allocate TLS if the DLL might be loaded with LoadLibrary.
123
124         Thus, in case when \p libcds or a dll that depends on \p libcds is loaded dynamically by calling \p LoadLibrary explicitly,
125         you should not use \p CDS_THREADING_MSVC macro. Instead, you should build your dll projects with \p CDS_THREADING_WIN_TLS only.
126     */
127     namespace threading {
128
129         //@cond
130         /// Thread-specific data
131         struct ThreadData {
132
133             //@cond
134             cds::urcu::details::thread_data< cds::urcu::general_instant_tag > *     m_pGPIRCU;
135             cds::urcu::details::thread_data< cds::urcu::general_buffered_tag > *    m_pGPBRCU;
136             cds::urcu::details::thread_data< cds::urcu::general_threaded_tag > *    m_pGPTRCU;
137 #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED
138             cds::urcu::details::thread_data< cds::urcu::signal_buffered_tag > *    m_pSHBRCU;
139             cds::urcu::details::thread_data< cds::urcu::signal_threaded_tag > *    m_pSHTRCU;
140 #endif
141
142             //@endcond
143
144             //cds::gc::HP::thread_gc_impl  * m_hpManager     ;   ///< Michael's Hazard Pointer GC thread-specific data
145             //cds::gc::DHP::thread_gc_impl * m_dhpManager    ;   ///< Dynamic Hazard Pointer GC thread-specific data
146
147             size_t  m_nFakeProcessorNumber  ;   ///< fake "current processor" number
148
149             //@cond
150             size_t  m_nAttachCount;
151             //@endcond
152
153             /// Per-thread elimination record
154             cds::algo::elimination::record   m_EliminationRec;
155
156             //@cond
157             static CDS_EXPORT_API atomics::atomic<size_t> s_nLastUsedProcNo;
158             static CDS_EXPORT_API size_t                  s_nProcCount;
159             //@endcond
160
161             //@cond
162             ThreadData()
163                 : m_pGPIRCU( nullptr )
164                 , m_pGPBRCU( nullptr )
165                 , m_pGPTRCU( nullptr )
166 #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED
167                 , m_pSHBRCU( nullptr )
168                 , m_pSHTRCU( nullptr )
169 #endif
170                 , m_nFakeProcessorNumber( s_nLastUsedProcNo.fetch_add(1, atomics::memory_order_relaxed) % s_nProcCount )
171                 , m_nAttachCount(0)
172             {}
173
174             ~ThreadData()
175             {
176                 assert( m_pGPIRCU == nullptr );
177                 assert( m_pGPBRCU == nullptr );
178                 assert( m_pGPTRCU == nullptr );
179 #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED
180                 assert( m_pSHBRCU == nullptr );
181                 assert( m_pSHTRCU == nullptr );
182 #endif
183             }
184
185             CDS_EXPORT_API void init();
186             CDS_EXPORT_API bool fini();
187
188             size_t fake_current_processor()
189             {
190                 return m_nFakeProcessorNumber;
191             }
192             //@endcond
193         };
194         //@endcond
195
196     } // namespace threading
197 } // namespace cds
198
199 #endif // #ifndef CDSLIB_THREADING__COMMON_H