Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9081485
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T20:19:35+00:00 2026-06-16T20:19:35+00:00

I hear that const means thread-safe in C++11 . Is that true? Does that

  • 0

I hear that const means thread-safe in C++11. Is that true?

Does that mean const is now the equivalent of Java‘s synchronized?

Are they running out of keywords?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T20:19:37+00:00Added an answer on June 16, 2026 at 8:19 pm

    I hear that const means thread-safe in C++11. Is that true?

    It is somewhat true…

    This is what the Standard Language has to say on thread-safety:

    [1.10/4]
    Two expression evaluations conflict if one of them modifies a memory location (1.7) and the other one accesses or modifies the same memory location.

    [1.10/21]
    The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior.

    which is nothing else than the sufficient condition for a data race to occur:

    1. There are two or more actions being performed at the same time on a given thing; and
    2. At least one of them is a write.

    The Standard Library builds on that, going a bit further:

    [17.6.5.9/1]
    This section specifies requirements that implementations shall meet to prevent data races (1.10). Every standard library function shall meet each requirement unless otherwise specified. Implementations may prevent data races in cases other than those specified below.

    [17.6.5.9/3]
    A C++ standard library function shall not directly or indirectly modify objects (1.10) accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function’s non-const arguments, including this.

    which in simple words says that it expects operations on const objects to be thread-safe. This means that the Standard Library won’t introduce a data race as long as operations on const objects of your own types either

    1. Consist entirely of reads –that is, there are no writes–; or
    2. Internally synchronizes writes.

    If this expectation does not hold for one of your types, then using it directly or indirectly together with any component of the Standard Library may result in a data race. In conclusion, const does mean thread-safe from the Standard Library point of view. It is important to note that this is merely a contract and it won’t be enforced by the compiler, if you break it you get undefined behavior and you are on your own. Whether const is present or not will not affect code generation –at least not in respect to data races–.

    Does that mean const is now the equivalent of Java‘s synchronized?

    No. Not at all…

    Consider the following overly simplified class representing a rectangle:

    class rect {
        int width = 0, height = 0;
    
    public:
        /*...*/
        void set_size( int new_width, int new_height ) {
            width = new_width;
            height = new_height;
        }
        int area() const {
            return width * height;
        }
    };
    

    The member-function area is thread-safe; not because its const, but because it consist entirely of read operations. There are no writes involved, and at least one write involved is necessary for a data race to occur. That means that you can call area from as many threads as you want and you will get correct results all the time.

    Note that this doesn’t mean that rect is thread-safe. In fact, its easy to see how if a call to area were to happen at the same time that a call to set_size on a given rect, then area could end up computing its result based on an old width and a new height (or even on garbled values).

    But that is alright, rect isn’t const so its not even expected to be thread-safe after all. An object declared const rect, on the other hand, would be thread-safe since no writes are possible (and if you are considering const_cast-ing something originally declared const then you get undefined-behavior and that’s it).

    So what does it mean then?

    Let’s assume –for the sake of argument– that multiplication operations are extremely costly and we better avoid them when possible. We could compute the area only if it is requested, and then cache it in case it is requested again in the future:

    class rect {
        int width = 0, height = 0;
    
        mutable int cached_area = 0;
        mutable bool cached_area_valid = true;
    
    public:
        /*...*/
        void set_size( int new_width, int new_height ) {
            cached_area_valid = ( width == new_width && height == new_height );
            width = new_width;
            height = new_height;
        }
        int area() const {
            if( !cached_area_valid ) {
                cached_area = width;
                cached_area *= height;
                cached_area_valid = true;
            }
            return cached_area;
        }
    };
    

    [If this example seems too artificial, you could mentally replace int by a very large dynamically allocated integer which is inherently non thread-safe and for which multiplications are extremely costly.]

    The member-function area is no longer thread-safe, it is doing writes now and is not internally synchronized. Is it a problem? The call to area may happen as part of a copy-constructor of another object, such constructor could have been called by some operation on a standard container, and at that point the standard library expects this operation to behave as a read in regard to data races. But we are doing writes!

    As soon as we put a rect in a standard container –directly or indirectly– we are entering a contract with the Standard Library. To keep doing writes in a const function while still honoring that contract, we need to internally synchronize those writes:

    class rect {
        int width = 0, height = 0;
    
        mutable std::mutex cache_mutex;
        mutable int cached_area = 0;
        mutable bool cached_area_valid = true;
    
    public:
        /*...*/
        void set_size( int new_width, int new_height ) {
            if( new_width != width || new_height != height )
            {
                std::lock_guard< std::mutex > guard( cache_mutex );
            
                cached_area_valid = false;
            }
            width = new_width;
            height = new_height;
        }
        int area() const {
            std::lock_guard< std::mutex > guard( cache_mutex );
            
            if( !cached_area_valid ) {
                cached_area = width;
                cached_area *= height;
                cached_area_valid = true;
            }
            return cached_area;
        }
    };
    

    Note that we made the area function thread-safe, but the rect still isn’t thread-safe. A call to area happening at the same time that a call to set_size may still end up computing the wrong value, since the assignments to width and height are not protected by the mutex.

    If we really wanted a thread-safe rect, we would use a synchronization primitive to protect the non-thread-safe rect.

    Are they running out of keywords?

    Yes, they are. They have been running out of keywords since day one.


    Source: You don’t know const and mutable – Herb Sutter

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i hear that NTFS alternate data streams can be used to hide running executabes.
I always hear that Java being open-source is a big benefit, but I fail
We have a Prepared Statement in Java and we hear that it is different
I always hear that reading a CAPTCHA is impossible and so now I want
It is very common to hear that C++ or Java should be used on
I hear that ECMAScript 5 is now getting supported by most of the latest
I hear that Data.Text is going to replace String s in future Haskell versions.
We all hear that math at least helps a little bit with programming. My
On the one hand, I read or hear that function calls are expensive and
I created an iPhone application for the App Store. I hear that some things

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.