lundi 26 août 2019

std::atomic

I thought comparing an std::atomic was thread safe. But the following code crashes sometimes at

assert(completionCount == 1);

Why does this happen and how to fix it?

Ticket ticket6(3);
std::atomic<int> completionCount(0);
void ticketTest() {
    std::thread thread1 = std::thread([] {
        if (!ticket6.isDone()) {
            ticket6.done();
        }
        bool shouldComplete = false;
        ticket6.waitUntilDone(shouldComplete);
        if (shouldComplete) {
            completionCount++;
        }
    });
    std::thread thread2 = std::thread([] {
        if (!ticket6.isDone())
            ticket6.done();
        bool shouldComplete = false;
        ticket6.waitUntilDone(shouldComplete);
        if (shouldComplete) {
            completionCount++;
        }
    });
    std::thread thread3 = std::thread([] {
        if (!ticket6.isDone())
            ticket6.done();
        bool shouldComplete = false;
        ticket6.waitUntilDone(shouldComplete);
        if (shouldComplete) {
            completionCount++;
        }
    });

    assert(!ticket6.isDone());
    assert(ticket6.getNumTasks() == 3);

    ticket6.waitUntilDone();

    assert(ticket6.isDone());
    assert(!ticket6.wasCancelled());

    assert(completionCount == 1);
    thread1.join();
    thread2.join();
    thread3.join();
}

Aucun commentaire:

Enregistrer un commentaire