Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use the idiomatic mode of C++

Shulou Source: shulou.com Published: 2022-06-01 19:50:47 09月13日 Update

This article mainly explains "how to use the idiomatic pattern of C++". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn "how C++ uses idiomatic patterns".

CP.111: if you really need a double-checked lock, use idiomatic mode

Reason (reason)

Double check locks tend to mess things up. If you really need to use double-checked locks, regardless of C++ core guidelines CP.100: do not use lock-free programming, unless absolutely necessary and C++ core guidelines CP.110: do not write double-checked locking code for initialization, then follow the idiomatic pattern when using double-checked locks.

When a non-thread-safe action is difficult to occur and there are quick thread-safety tests to ensure that it is not needed, but there is no guarantee to the contrary, a double-checked lock mode that does not violate the C++ core guideline CP.110: do not write double-checked locking code for initialization.

Example, bad (negative example)

The use of volatile does not make the first check thread-safe, see also CP.200: Use volatile only to talk to non-C++ memory

The use of volatile does not allow the first to check thread safety, see CP.200: use volatile only when talking about non-C++ memory

Mutex action_mutex

Volatile bool action_needed

If (action_needed) {

Std::lock_guard lock (action_mutex)

If (action_needed) {

Take_action ()

Action_needed = false

}

} Example, good (sample) mutex action_mutex

Atomic action_needed

If (action_needed) {

Std::lock_guard lock (action_mutex)

If (action_needed) {

Take_action ()

Action_needed = false

}

}

Fine-tuned memory order may be beneficial where acquire load is more efficient than sequentially-consistent load

When sequential execution loads are more efficient than demand loads, it may be more advantageous to adjust a good memory order

Mutex action_mutex

Atomic action_needed

If (action_needed.load (memory_order_acquire)) {

Lock_guard lock (action_mutex)

If (action_needed.load (memory_order_relaxed)) {

Take_action ()

Action_needed.store (false, memory_order_release)

}

}

Thank you for your reading. the above is the content of "how to use idiomatic patterns on C++". After the study of this article, I believe you have a deeper understanding of how C++ uses idiomatic patterns. Specific use also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Caching checking patterns guidelines Security Core Thread Learning Code memory content Action situation order guarantee good necessary thing cause negative Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno vpn Linux macOS NVidia