Size Functions and Thread Safety in C ++

I wonder if size functions (size, length, or something else) are thread safe? As I understand it, they usually just return part of their private size. I really doubt that they make any calculations. They are all marked as const, but are they thread safe? e.g. std :: list :: size?

I have a lock protection function for writing and another for reading (also locked), but I wonder if my count function should also be locked? IMO, this looks like a waste of response time. I don't think this could break any iterators or crash if some member is removed from the list at the same time (as much as possible).

+6
source share
2 answers

Yes, it must be protected by a lock. Say your implementation of 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, the second thread can interrupt the first one that read the size after the first read, update the size variable, and then, when the second 16-bit read occurs, you can get a real corrupt value for the size.

+6
source

No, they are not thread safe. Standard containers are simply not thread safe, period.

However, there is a limited degree of thread safety: if each thread accesses another element and no element accesses two separate threads at any given time, then this is fine. However, any operation that mutates the container itself (insertion, erasure) is not thread safe and should be synchronized. Consequently, iterators and links can lose their relevance, as well as size() .

In other words, if you separate all operations that mutate the container from those that don't, then as long as you don't mutate, you can safely call size() from multiple threads.

+4
source

Source: https://habr.com/ru/post/906959/


All Articles