+ 2

thread safe and const member function

Hi I read somewhere that const member functions are always thread safe as it is read only operation on member variables. But what if other function is modifying the data which we are reading?

24th Jan 2025, 12:57 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
9 Réponses
+ 2
const member functions are thread safe in of itself, but it doesn't guarantee thread safety everywhere else. https://stackoverflow.com/questions/67143880/what-is-the-definition-of-a-thread-safe-function-according-to-the-c11-languag
25th Jan 2025, 2:23 AM
Bob_Li
Bob_Li - avatar
+ 2
Ketan Lalcheta the const memeber functions are nothing but the constant values which cannot be changed after defining it. So if you don't want the variable values to get changed you can use const memeber function for achieving it as any other functions can't change the values of it.
24th Jan 2025, 3:30 PM
Aysha
+ 2
atomic? volatile have conflicting pros and cons... https://stackoverflow.com/questions/4557979/when-to-use-volatile-with-multi-threading Feeding changing data to threads is tricky and error prone...
24th Jan 2025, 4:28 PM
Bob_Li
Bob_Li - avatar
+ 1
Hi Bob_Li, Atomic is very low level and need more care. I would go with mutex then but point is that const member function is not automatically thread safe and need some mechanism be it atomic or mutex. Right?
24th Jan 2025, 4:38 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
HI Aysha Could not agree more...! Const member function can have access of any member variables. It just a guarantee to compiler that this const function will not modify anything.
24th Jan 2025, 4:39 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
What do you mean by const member function, like its arguments are const? I havent studied those definitons in a very long time
25th Jan 2025, 1:50 PM
Run Of The Mill{Whats 1+1 again?}
Run Of The Mill{Whats 1+1 again?} - avatar
+ 1
Thanks Bob_Li
25th Jan 2025, 2:06 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
no. Argument is not which decides function is const or not void display(clsTest& obj ) const This function is constant function and it guarantees that any class member will not be modified in the method. Local variables can be modified as well as argument also can be modified as argument is non const. Argument can or cannot be const for const member function. Const member function must be a class function only
25th Jan 2025, 2:09 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Lalcheta thank you! I havent worked with them in awhile. (Also I know that the function isnt const because of its args)
25th Jan 2025, 2:57 PM
Run Of The Mill{Whats 1+1 again?}
Run Of The Mill{Whats 1+1 again?} - avatar