Programming Reference | Multi-task data access synchronization version = m_Version; return S_OK; }; private: T_Version m_Version; }; BEGIN_INTERFACE_MAP(VersionProvider) INTERFACE_ENTRY(IID_ITcVersionProvider, ITcVersionProvider) END_INTERFACE_MAP() class MySingleton { public: static MySingleton& Instance(ITcVersionProvider* ip = NULL, bool bRelease=false) { static MySingleton g_instance(ip); if (bRelease) g_instance.Release(); return g_instance; } T_Version GetVersion() { T_Version v = {0, 0, 0, 0}; if (m_spTcInst != NULL) { m_spTcInst->GetVersion(v); } return v; } private: MySingleton(ITcVersionProvider* ip = NULL) :
m_spTcInst(ip) { } void Release() { m_spTcInst = NULL; } ITcVersionProviderPtr m_spTcInst; }; Here the usage is shown:
// actual instance which is an example for a TwinCAT resource VersionProvider vp; // Initialize singleton MySingleton::Instance(&vp); // use singleton to access information provided by TwinCAT resource T_Version v1 = MySingleton::Instance().GetVersion(); Assert::IsTrue( v1.major == 1 && v1.minor == 2 && v1.build == 3 && v1.revision == 0); // Deinitialize singleton and release reference to TwinCAT resource MySingleton::Instance(NULL, true); // use singleton after deinitialization which has to implement some default behaviour for this case T_Version v2 = MySingleton::Instance().GetVersion(); Assert::IsTrue( v2.major == 0 && v2.minor == 0 && v2.build == 0 && v2.revision == 0); 12.7 Multi-task data access synchronization | Multi-task data access synchronization When one set of data is accessed by multiple tasks, the tasks may access the same data simultaneously, depending on the task/real-time configuration.
If the data is written by at least one of the tasks, the data may have an inconsistent state during or after a change. To prevent this, all concurrent accesses must be synchronized so that only one task can access the shared data at a time. If the same data is accessed by several tasks and the data is written for at least one of these accesses, all read and write accesses must be synchronized. This applies regardless of whether the tasks are run on a single or multiple CPU cores. WARNING Inconsistencies and other risks due to unsecured data access If concurrent accesses are not synchronized, there is a risk that the data records will be inconsistent or invalid.
Depending on how the data is used in the further course of the program, this can result in incorrect program behavior, undesired axis movement, or even a sudden program standstill. Damage to equipment and workpieces may occur, or people's health and lives may be endangered, depending on the controlled system. TwinCAT 3 153 Version: 1.19.1