25
25
#include < fastrtps/types/AnnotationDescriptor.h>
26
26
#include < fastrtps/utils/md5.h>
27
27
#include < fastdds/dds/log/Log.hpp>
28
+ #include < atomic>
28
29
#include < sstream>
29
30
30
31
namespace eprosima {
@@ -42,26 +43,51 @@ class TypeObjectFactoryReleaser
42
43
43
44
};
44
45
46
+ enum class TypeObjectFactoryInstanceState
47
+ {
48
+ NOT_CREATED = 0 , // Instance has not been created
49
+ CREATING = 1 , // Instance is being created
50
+ CREATED = 2 , // Instance has been created
51
+ DESTROYING = 3 // Instance is being destroyed
52
+ };
53
+
54
+ static std::atomic<TypeObjectFactoryInstanceState> g_instance_state{TypeObjectFactoryInstanceState::NOT_CREATED};
45
55
static TypeObjectFactoryReleaser s_releaser;
46
56
static TypeObjectFactory* g_instance = nullptr ;
57
+
47
58
TypeObjectFactory* TypeObjectFactory::get_instance ()
48
59
{
49
- if (g_instance == nullptr )
60
+ TypeObjectFactoryInstanceState expected_state = TypeObjectFactoryInstanceState::NOT_CREATED;
61
+
62
+ // Wait until the instance is either created or destroyed
63
+ while (!g_instance_state.compare_exchange_weak (expected_state, TypeObjectFactoryInstanceState::CREATING))
50
64
{
51
- auto instance = new TypeObjectFactory ();
52
- g_instance = instance;
53
- g_instance->create_builtin_annotations ();
54
- return instance;
65
+ // If it is already created, return it
66
+ if (expected_state == TypeObjectFactoryInstanceState::CREATED)
67
+ {
68
+ return g_instance;
69
+ }
70
+
71
+ // Prepare for retry
72
+ expected_state = TypeObjectFactoryInstanceState::NOT_CREATED;
55
73
}
56
- return g_instance;
74
+
75
+ auto instance = new TypeObjectFactory ();
76
+ instance->create_builtin_annotations ();
77
+ g_instance = instance;
78
+ g_instance_state.store (TypeObjectFactoryInstanceState::CREATED);
79
+
80
+ return instance;
57
81
}
58
82
59
83
ReturnCode_t TypeObjectFactory::delete_instance ()
60
84
{
61
- if (g_instance != nullptr )
85
+ TypeObjectFactoryInstanceState expected_state = TypeObjectFactoryInstanceState::CREATED;
86
+ if (g_instance_state.compare_exchange_strong (expected_state, TypeObjectFactoryInstanceState::DESTROYING))
62
87
{
63
88
delete g_instance;
64
89
g_instance = nullptr ;
90
+ g_instance_state.store (TypeObjectFactoryInstanceState::NOT_CREATED);
65
91
return ReturnCode_t::RETCODE_OK;
66
92
}
67
93
return ReturnCode_t::RETCODE_ERROR;
0 commit comments