vendredi 26 mai 2023

Is there any way I can lock a list of mutex?

My code is like the following. A Element holds a pointer to a mutex, and there is a vector that holds all Elements.

If I know the count of elements at compile time, I can construct a scoped_lock to lock all these mutexes. However, I don't know the size of the vector now. So how can I lock all the mutexes and generate a lock guard safely?

#include <vector>
#include <mutex>

struct Element {
    Element() {
        mut = new std::mutex();
    }
    Element(Element && other) : mut(other.mut) {
        other.mut = nullptr;
    }
    ~Element() { delete mut; }
    std::mutex * mut;
};

int main() {
    std::vector<Element> v;
    v.push_back(Element());
    v.push_back(Element());
    v.push_back(Element());

    std::scoped_lock(*v[0].mut, *v[1].mut, *v[2].mut);
}

Aucun commentaire:

Enregistrer un commentaire