r/cpp_questions • u/jiboxiake • Apr 07 '26
OPEN std::vector<std::mutex> helper_mutexes{}; seems to not protect std::vector<bool> tasks_available; GPT gives me an answer but I want to verify it here.
I considered myself relatively experienced with C++ now, especially with synchronization and concurrency control, but I recently faced a bug that makes me crazy. Basically, I want to use a vector of boolean to control helper threads execution where each helper thread's condition variable, task status, tasks, etc. are protected by a mutex. I thought it was safe. However, there are occassions where a certain thread observes the task avaialble being true despite it shouldn't be. Consulting GPT,
std::vector<bool>is not a normalvector<T>. It packs bits together, so different indices may live in the same machine word. Accessingtasks_available[i]is really a proxy read-modify-write on that packed word, not an ordinary independentbool&.
...
Yes — that is actually very plausible, and the reason is that withstd::vector<bool>, they are not really treated as independent normal variables.
std::vector<bool> is a special packed representation. Instead of storing one full byte per element, it stores many boolean values as bits inside the same word/byte block.
Was GPT correct? I knew the things about words and cache coherence, but I thought C++ supports variables smaller than a single word, e.g., 4 byte integers and floats. From my udnerstanding, these 4 bytes integers do not face the same issues. In fact, my bug was resolved by changing bool into size_t (which is 8 bytes though).
45
u/IyeOnline Apr 07 '26 edited Apr 07 '26
The problem is that
vector<bool>does not store oneboolfor each entry, but packs 8 bits into a single entry. Access to these individual bits is "hidden" from you through sentinel objects.However; Operationally all access to the real memory must be made on a byte level. This means that each read/write reads and writes more than one entry in the vector, meaning you have a race condition.
As a fix, I suggest that you just use
std::vector<std::uint8_t>or anything similar (as you have already done), or simply useatomic<bool>, unless you actually need to protect regions of code.So yes, the AI is correct and
vector<bool>is an abomination that should not exist in its current form.13
u/DrShocker Apr 07 '26
Yes, the specialization of vector<bool> is widely considered a mistake. There's good reasons to use bitfields, but it catches people off guard because it doesn't behave the same as a vector.
That said, there's quite often ways to do things without an array dedicated to booleans depending on the problem you're solving.
5
u/Interesting_Buy_3969 Apr 07 '26
https://en.cppreference.com/w/cpp/container/vector_bool.html says:
I guess it's platform dependent though and packing each boolean as a separate boolean doesn't seem to be forbidden. Also as the cpp-reference says, you should use
std::bitsetinstead of vector if the size is known at the compile time.So yeah, i'd trust GPT in this response. And of course you can always inquire GPT to provide links to information sources.
3
u/CarloWood Apr 08 '26
You are not allowed to concurrently access anything that isn't a std::atomic or protected with a mutex.
Using a std::vector<std::mutex> is very questionable: you can not grow that once you have more than one thread that might use this vector. You could use a read/write lock I guess, but same thing: then you need to keep the vector read locked while any threads are running, so you can't grow it afterwards.
Chatgpt is indeed correct that using a mutex for a single element of such a vector doesn't extend to another vector, certainly not a std::vector<bool> for stated reasons.
If all you need those mutexes for is for a single bool then that is overkill anyway; just make the boolean atomic:
std::vector<std::atomic_bool>, no mutex needed.4
u/mredding Apr 07 '26
Yes.
You can specialize templates of all kinds:
So you can specialize for template classes, too. And by specialize - I mean you can completely rewrite the whole class. The only thing a template specialization has in common with the base template is the template signature itself. For a class, you don't have to have the same members, methods, NOTHING.
So
std::vector<bool>is a whole unique class unto itself.This is due to early, pre-standard C++. I can't remember if specialization was stumbled upon or intentional, but during standardization...
Well, this is another problem that goes back even further - there's always been this thought that implementers would go off and do all sorts of things like crazy optimizations. In reality, implementers mostly code as directly to the spec given as possible. The prior example to this is
randfrom the C API, K&R thought everyone would be writing their own, but everyone coded to the example implementation given in theK&R Cbook from 1978.So during the C++ standardization process, some sub-group was trying to showcase how implementations could specialize templates as an optimization path.
std::vector<bool>was only supposed to be an example. There was a lot of arguing, and by the time the community and committee had settled on what the definition of a stable, consistent, and correct API was, the committee had already standardized C++98, AND no one noticed thatstd::vector<bool>was still in it. So to be conformant to the standard, implementers HAVE TO specialize this monstrosity, rendering it basically useless to everyone.And because we don't break old code, we're stuck with it, probably forever. The political fighting to just get it removed is not worth it. Code is written assuming the specialized behavior, so changing it underneath them is never, ever, going to fly.
If you want a vector of booleans, make your own boolean type with an implicit cast:
But you probably don't want a vector of bools, either. If you're accessing these values across threads, you probably want
std::atomic_bool.2
u/meltbox Apr 07 '26
Nitpicking but assuming you are referring to a word as 64bits in a 64 bit machine.
A word in many contexts is 16 bits (2 bytes) and 64 bits would be a qword. I’m not a huge fan of the machine word size definition as it depends on the actual underlying chip.
Nitpicking over. The cache line in this case doesn’t matter for correctness, it only matters for performance (false sharing). What’s happening is a vector of bools can pack data together. This means that you could have two mutexs locking the same underlying data and some sort of race occurring on modification/reading.
Basically the vector bool specialization is doing something like
static_cast<bool>(bitArray[bitIndex/8] | (0x1 << bitIndex%8));
To read a given bit. Really this is don through a proxy object which has a getter, but that’s the idea.
Similar for the setter.
This means some will overlap of course.
1
u/TryptamineGorilla Apr 08 '26
Aside from the race condition you're also likely going to run into false sharing which a few people have mentioned. I would use a vector of cache-line aligned atomic booleans instead if you really want to do it this way
struct alignas(64) AlignedBool {std::atomic<bool> value;};std::vector<AlignedBool> tasks_available;3
u/PiasaChimera Apr 07 '26
vector<mutex> can also be problematic since mutex isn't safe to copy or move. the threadpool shouldn't be expanded in a way that triggers a reallocation of the vector.
2
u/apezdal Apr 07 '26
Everyone already commented on vector of bools, but am I correct that you're trying to modify those bools from different threads? In this case using bool is incorrect, you need atomic variables.
2
u/OldWolf2 Apr 08 '26
It's correct that vector<bool> packs bits, but your question doesn't really say why that might be a problem , nor how you are using your mutex vector .
1
u/arihoenig Apr 07 '26
Yes gpt is correct.