example2_use_with_unique_lock.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <thread>
#include <mutex>

class Account {
public:
    Account(int balance) : balance_(balance) {}
    
    void transfer(Account& to, int amount) {
        std::unique_lock<std::mutex> lock_from(mutex_, std::defer_lock);
        std::unique_lock<std::mutex> lock_to(to.mutex_, std::defer_lock);
        std::lock(lock_from, lock_to);
        
        if (balance_ >= amount) {
            balance_ -= amount;
            to.balance_ += amount;
            std::cout << "Transfer successful\n";
        } else {
            std::cout << "Insufficient funds\n";
        }
    }

private:
    int balance_;
    std::mutex mutex_;
};

int main() {
    Account acc1(1000);
    Account acc2(500);

    std::thread t1(&Account::transfer, &acc1, std::ref(acc2), 300);
    std::thread t2(&Account::transfer, &acc2, std::ref(acc1), 200);

    t1.join();
    t2.join();

    return 0;
}
Back to std_lock