#21 Support for logical constness

Markus Elfring

Would you like to add support for the C++ key word

A function signature like "int
worker_fifo::get_nthreads() const" would become useable


  • John Skaller
    John Skaller

    Logged In: YES

    I'm not sure what you mean by 'adding support'. Do you mean,
    you think it would have been better to use a mutable member
    in this instance?

    I thought of that briefly, but in the end decided to just
    chuck out the 'const', since I have learned over the years
    that C++ gets it wrong a lot.

    In this case, it isn't even clear get_nthreads() really is
    logically const.

    In fact .. it isn't clear why nthreads needs to be protected
    by a mutex. That assumes someone other than the owner thread
    can change the number of threads in the job pool ..and that
    doesn't make sense: there could be contention. Serialising
    the thread count will not resolve the contention. In fact
    the 'set_nthreads()' function will fail if two threads both
    call it.

    So actually, your original suggestion is probably wrong:
    nthreads doesn't need protection, it is set_nthreads() that
    needs protection: it needs to be available only to the
    owner, and in that case access will be serial anyhow and
    doesn't require serialisation by a mutex :)

    The only way to enforce this would be to store the current
    thread ID and check it on entry to that function (and others
    that modify it).

  • Markus Elfring
    Markus Elfring

    • summary: Supprt for logical constness --> Support for logical constness
  • Markus Elfring
    Markus Elfring

    Logged In: YES

    Yes, a mutable member is better - I know a few use cases
    that are more appropriate than the current example.

    More explanations are in the answer for the question 'What
    do I do if I want a const member function to make an
    "invisible" change to a data member?'

    Please keep in mind:
    Each attribute that can be changed by multiple threads must
    be protected with mutual exclusion für write and read access.
    A mutex does all synchronisation you need for you. Don't
    think about to fiddle with thread IDs.