How can I properly increase C ++ 11 std :: atomic?

I am new to multi-threaded programming and I found std::atomicin C ++ 11.

So, I tried to figure out how much time atomic operations take.

I tried this code:

using namespace std;
using namespace std::chrono;

constexpr int NUM_THREADS = 8;
constexpr int LIMIT = 100000;

atomic<int> sum = 0;

void foo(int idx) {
    while (true) {
        if (sum.load() >= LIMIT) {
            return;
        }
        sum.fetch_add(1);
    }
}

with main:

int main(void) {
    thread threads[NUM_THREADS];

    auto start = high_resolution_clock::now();

    for (int i = 0; i < NUM_THREADS; i++) {
        threads[i] = thread(&foo, i);
    }

    for (int i = 0; i < NUM_THREADS; i++) {
        threads[i].join();
    }
    auto du = high_resolution_clock::now() - start;

    cout << "computing time\t\t" << duration_cast<milliseconds>(du).count() << "ms" << endl;
    cout << "number of thread\t" << NUM_THREADS << endl;
    cout << "sum\t\t\t" << sum << endl;

    return 0;
}

But sumnot always the same as LIMIT.

As far as I know, atomic operations are thread-safe when called. So yes, I think my code is wrong, but I could not figure out how to make this work properly.

How can I get the correct result using main?

(well, this version will do sum, and LIMITequal, but I think it's not very good ...)

void foo(int idx) {
    for (int i = 0; i < LIMIT / NUM_THREADS; i++) {
        sum.fetch_add(1);
    }
}
+4
2

, , , .

, . :

while (true) {
    auto current = sum.load();        
    if (current >= LIMIT) {
        return;
    }
    auto next = current + 1;
    sum.compare_exchange_strong(current, next));
}
+5

operator++ , , , :

void foo(int idx) {
    while (true) {
        if (sum++ >= LIMIT) {
            return;
        }
    }
}

sum LIMIT, , LIMIT . : , std::numeric_limits<int>::max() - LIMIT, sum int. LIMIT , .

-1

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


All Articles