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).
A threadsafe function protects shared resources from concurrent access by locks. Thread safety concerns only the implementation of a function and does not affect its external interface. In C language, local variables are dynamically allocated on the stack.
No, they're not thread-safe.
Pure functions are easier to parallelize “If there is no data dependency between two pure expressions, then their order can be reversed, or they can be performed in parallel and they cannot interfere with one another (in other terms, the evaluation of any pure expression is thread-safe).”
Yes, it needs to be protected by a lock. Let's say that your implementation's std::list::size
is 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With