I have a class as follows. I want to hold 2 member variable as a atomic. One will hold the current value and the other the maximum value. If the current number is greater than the maximum number, the maximum number will be updated. Is function thread safe? Is there any problem like infinite loop or etc.? I wanted to ask because I'm not quite sure. If you have a better solution, can you suggest it? Thank you.
`
#include <atomic>
class Myclass {
public:
void inc() {
std::size_t cur_count = (++_curCount);
std::size_t max_count = _maxCount.load();
if(cur_count > max_count) {
while(!_maxCount.compare_exchange_strong(max_count, cur_count) && cur_count >max_count)
;
}
}
private:
std::atomic<std::size_t> _maxCount{0};
std::atomic<std::size_t> _curCount{0};
};
`
I just want to be sure the code is thread-safe.