Thread-Safe object lifetime Management resolves object constructs for thread safety
- When we need to dynamically allocate objects (lazy loading), there may be multiple initialization problems if you run this part of the code in multiple threads.
Single-Case mode
Initialization of a static variable after C + + 11 is thread-safe. You can use static variables to implement a singleton pattern to solve repetitive initialization problems.
Std::call_once
Personal feeling is not graceful enough to pass a flag to identify the initialization situation
Thread access to uninitialized resources
For example, in the thread class, Std::thread is constructed immediately after the execution of the thread function, but the resources accessed in the function may not have been initialized.
Solution:
- Member initialization List control construction order
- To manually control the running of a thread function
- Do not divulge this pointer
Addressing thread safety for object destruction
- The problem of object destruction is a particular thread-safety problem, how do we know that there are no other threads using it when we deconstruct the object? When we use this object, how can we ensure that it is not deconstructed (as a wild pointer)?
Solution Solutions
Use shared_ptr and unique_ptr to control the life cycle and use custom destructors to provide compatibility.
Use WEAK_PTR to detect the life cycle of shared_ptr and avoid ring references
Attention
The reference count for shared_ptr is secure and unlocked, but it itself needs to be locked (there are two pointers, and the internal is a two-segment operation).
Using Shared_from_this
Use Std::move + std::unique_ptr for unique resources
Thread-Safe Object lifetime management