Do I need to use atomic<> if already guard by mutex

Viewed 3004

Given the code in this post, to implement Semaphore using only atomic<> and mutex.

I'm just curious that since count is already guarded by updateMutex, is atomic<> necessary?

struct Semaphore {
    int size;
    atomic<int> count;
    mutex updateMutex;

    Semaphore(int n) : size(n) { count.store(0); }

    void aquire() {
        while (1) {
            while (count >= size) {}
            updateMutex.lock();
            if (count >= size) {
                updateMutex.unlock();
                continue;
            }
            ++count;
            updateMutex.unlock();
            break;
        }
    }

    void release() {
        updateMutex.lock();
        if (count > 0) {
            --count;
        } // else log err
        updateMutex.unlock();
    }
};

Without atomic, I think the constructor would get synchronization problem. Assignment to count might not be visible if other threads are using it right after the construction.

If so, what about size? Does it also need to be protected by atomic<>?

Or the atomic<> is totally useless because both size and count will be visible no matter when other threads use them.

Thanks!

3 Answers
Related