I was using vector<atomic<bool>> in C++, the code is here:
#include <iostream>
#include <thread>
#include <atomic>
#include <vector>
using namespace std;
int main() {
int n = 10;
int count = 20;
vector<atomic<bool>> flags(n);
vector<thread> jobs;
for (int i = 0; i < count; i++) {
jobs.emplace_back([&](){
bool old_val = false;
for (int i = 0; i < n; i++) {
if (flags[i].compare_exchange_strong(old_val, true)) {
cout<<1;
break;
}
}
});
}
for (int i = 0; i < count; i++) {
jobs[i].join();
}
return 0;
}
I don't know why, no matter what the value of variable count is, the output content is always "11111", which means that the compare_exchange_strong() only succeeds 5 times, half of the length of the vector<atomic<bool>>.
I expect the output would be 1111111111(ten 1s).
Can anyone tell me why? Thanks!!!!
You're reusing the same variable for each exchange, so if flags[i] is true on the first iteration, old_flags will be true on the second.
Then, if flags[i] is false on the third iteration, old_flags becomes false again.
This flip-flopping means that you only modify every other element in flags.
Move the declaration bool old_val = false; inside the loop.
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