Thread-Safe Object lifetime management

Source: Internet
Author: User
Tags thread class

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:

  1. Member initialization List control construction order
  2. To manually control the running of a thread function
  3. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.