Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size functions and thread-safety in C++

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).

like image 472
Pijusn Avatar asked Jan 26 '12 17:01

Pijusn


People also ask

What is thread-safe function in C?

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.

Is std :: list size () thread-safe?

No, they're not thread-safe.

Are pure functions 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).”


1 Answers

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.

like image 92
Praetorian Avatar answered Sep 17 '22 14:09

Praetorian