How does volatile ensure that the compiler does not make its own claim to undermine the security of multithreading.

Source: Internet
Author: User
Volatile

In Andrei Alexandrescu's article volatile-multithreaded programmer's best friend [2], the following is a brief description:

The volatile keyword was devised to prevent compiler optimizations that might render Code incorrect in the presence of certain asynchronous events. for example, if you declare a primitive variable as volatile, the compiler is not permitted to cache it in a register -- a common optimization that wocould be disastrous if that variable were shared among multiple threads. so the general rule is, if you have variables of primitive type that must be shared among multiple threads, declare those variables volatile. but you can actually do a lot more with this keyword: You can use it to catch code that is not thread safe, and you can do so at compile time. this article shows how it is done; the solution involves a simple smart pointer that also makes it easy to serialize critical sections of code.

Volatile modified variables are mainly used in multi-threaded programs to prevent optimization. Avoid Compiler optimization. When the compiler is optimizing, it sometimes retrieves some values and directly accesses them from the registers rather than from the memory. This optimization is no problem in a single-threaded program, however, in a multi-threaded program, because multiple threads run concurrently, it is possible that a thread has changed a public variable, and the value of registers in other threads has expired, however, this thread does not know it. If it is not changed and is still obtained from the register, the program runs undefined.

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.