I wonder if size functions (size, length or whatever) are thread safe? They usually just return some private size member, as I understand. I really doubt they do any sort of calculations. They all are marked as const but are they thread-safe? for example std::list::size?
I have a lock-protected function for writing and another for reading (also lock-protected) but I wonder if my count function should also be lock-protected? IMO, it looks like a waste of response time. I don’t think it may break any iterators or fail if some member is being removed from the list at the same time (as same, as possible).
Yes, it needs to be protected by a lock. Let’s say that your implementation’s
std::list::sizeis a 32-bit value but on your platform 32-bit reads are not atomic, they take 2 16-bit reads. In this case, a second thread may interrupt the first that was reading the size after the first read has occurred, update the size variable and then when the second 16-bit read takes place you may get a real messed up value for size.