Thread-safe object lifetime management

Thread-safe object lifetime management

Resolving thread safety of object construction

  • When we need to dynamically allocate objects (lazy loading), if we run this part of the code in multiple threads, there may be multiple initialization problems.

singleton pattern

The initialization of static variables after c++11 is thread-safe. You can use static variables to implement the singleton pattern to solve the problem of repeated initialization.

std::call_once

Personally, I feel that it is not beautiful enough, so I need to pass a flag to identify the initialization situation.

Thread accesses uninitialized resource

For example, in the Thread class, std::thread starts executing the function in the thread immediately after it is constructed, but the resources accessed in the function may not have been initialized.
solution:

  1. Member initialization lists control construction order
  2. Manually control the running of thread functions
  3. Don't leak this pointer

Solve the thread safety of object destructor

  • The problem of object destruction is a special thread safety problem. How do we know whether other threads are using it when we destroy this object? How can we ensure that it is not destructed (became a wild pointer) when we use this object?

solution

Use shared_ptr and unique_ptr to control life cycle, use custom destructor to provide adaptability.
Use weak_ptr to detect the life cycle of shared_ptr and avoid circular references

Notice

The reference count of shared_ptr is safe and lock-free, but it itself needs to be locked (there are two pointers, and the internal is a two-stage operation).
Use shared_from_this
to use std::move + std::unique_ptr for unique resources

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325028267&siteId=291194637