Deallocate wxThreadSpecificInfo when wxThread ends.
[wxWidgets.git] / src / common / threadinfo.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/threadinfo.cpp
3 // Purpose: declaration of wxThreadSpecificInfo: thread-specific information
4 // Author: Vaclav Slavik
5 // Created: 2013-09-14
6 // Copyright: (c) 2013 Vaclav Slavik <vslavik@fastmail.fm>
7 // Licence: wxWindows licence
8 ///////////////////////////////////////////////////////////////////////////////
9
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
12
13 #if defined(__BORLANDC__)
14 #pragma hdrstop
15 #endif
16
17 #include "wx/private/threadinfo.h"
18
19 #if wxUSE_THREADS
20
21 #include "wx/tls.h"
22 #include "wx/thread.h"
23 #include "wx/sharedptr.h"
24 #include "wx/vector.h"
25
26 namespace
27 {
28
29 // All thread info objects are stored in a global list so that they are
30 // freed when global objects are destroyed and no memory leaks are reported.
31 wxCriticalSection g_csAllThreadInfos;
32 typedef wxVector< wxSharedPtr<wxThreadSpecificInfo> > wxAllThreadInfos;
33 wxAllThreadInfos g_allThreadInfos;
34
35 // Pointer to currenct thread's instance
36 wxTLS_TYPE(wxThreadSpecificInfo*) g_thisThreadInfo;
37
38 } // anonymous namespace
39
40
41 wxThreadSpecificInfo& wxThreadSpecificInfo::Get()
42 {
43 if ( !wxTLS_VALUE(g_thisThreadInfo) )
44 {
45 wxTLS_VALUE(g_thisThreadInfo) = new wxThreadSpecificInfo;
46 wxCriticalSectionLocker lock(g_csAllThreadInfos);
47 g_allThreadInfos.push_back(
48 wxSharedPtr<wxThreadSpecificInfo>(wxTLS_VALUE(g_thisThreadInfo)));
49 }
50 return *wxTLS_VALUE(g_thisThreadInfo);
51 }
52
53 void wxThreadSpecificInfo::ThreadCleanUp()
54 {
55 if ( !wxTLS_VALUE(g_thisThreadInfo) )
56 return; // nothing to do, not used by this thread at all
57
58 // find this thread's instance in g_allThreadInfos and destroy it
59 wxCriticalSectionLocker lock(g_csAllThreadInfos);
60 for ( wxAllThreadInfos::iterator i = g_allThreadInfos.begin();
61 i != g_allThreadInfos.end();
62 ++i )
63 {
64 if ( i->get() == wxTLS_VALUE(g_thisThreadInfo) )
65 {
66 g_allThreadInfos.erase(i);
67 wxTLS_VALUE(g_thisThreadInfo) = NULL;
68 break;
69 }
70 }
71 }
72
73 #else // !wxUSE_THREADS
74
75 wxThreadSpecificInfo& wxThreadSpecificInfo::Get()
76 {
77 static wxThreadSpecificInfo s_instance;
78 return s_instance;
79 }
80
81 #endif // wxUSE_THREADS/wxUSE_THREADS