+ 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?
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
+ 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.
+ 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...
+ 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?
+ 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.
+ 1
What do you mean by const member function, like its arguments are const? I havent studied those definitons in a very long time
+ 1
Thanks Bob_Li
+ 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
0
Ketan Lalcheta thank you! I havent worked with them in awhile. (Also I know that the function isnt const because of its args)