mercredi 16 septembre 2020

Why do we need std::unique_lock and std::lock_guard in c++? [duplicate]

Here are two solutions of leetcode 1114 (concerning about mutex):

class Foo {
    mutex mtx_1, mtx_2;
    unique_lock<mutex> lock_1, lock_2;
public:
    Foo() : lock_1(mtx_1, try_to_lock), lock_2(mtx_2, try_to_lock) {
    }

    void first(function<void()> printFirst) {
        printFirst();
        lock_1.unlock();
    }

    void second(function<void()> printSecond) {
        lock_guard<mutex> guard(mtx_1);
        printSecond();
        lock_2.unlock();
    }

    void third(function<void()> printThird) {
        lock_guard<mutex> guard(mtx_2);
        printThird();
    }
};
class Foo {
    mutex lock1, lock2;
public:
    Foo() {
        lock1.lock();
        lock2.lock();
    }

    void first(function<void()> printFirst) {
        printFirst();
        lock1.unlock();
    }

    void second(function<void()> printSecond) {
        lock1.lock();
        printSecond();
        lock1.unlock();
        lock2.unlock();
    }

    void third(function<void()> printThird) {
        lock2.lock();
        printThird();
        lock2.unlock();
    }
};

The first solution used std::unique_lock and std::lock_guard to achieve the same effect as the second did, with less and read-easier code.

So These two stuffs are just wrappings for std::mutex which makes it more complicated to use, why do we actually need them?

Aucun commentaire:

Enregistrer un commentaire