Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A strange thing about vector<atomic<bool>> under multi-thread circumstance in C++

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!!!!

like image 784
yilin cai Avatar asked Oct 16 '25 00:10

yilin cai


1 Answers

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.

like image 98
molbdnilo Avatar answered Oct 17 '25 14:10

molbdnilo