vendredi 21 avril 2017

std::atomic_flag and std::lock_guard

Since std::lock_guard doesn't work with std::atomic_flag I've implemented my own version:

class atomic_guard {
    public:
    inline atomic_guard(std::atomic_flag& lock) : lock(lock) {
        while (this->lock.test_and_set()) {
            /* spin */ 
        };
    };

    inline ~atomic_guard() {
        this->lock.clear();
    };

    private:
    std::atomic_flag& lock;
};

This seems to work fine. The question is: is this a correct way to implement RAII for std::atomic_flag? Also is there a built-in guard for that? If not, why? The specialization std::lock_guard<std::atomic_flag> looks like something very natural.

Aucun commentaire:

Enregistrer un commentaire