What's the proper way to associate a mutex with its data?

前端 未结 8 1408
轮回少年
轮回少年 2021-02-05 23:44

In the classic problem of transferring money from one bank account to another, the accepted solution (I believe) is to associate a mutex with each bank account, then lock both b

8条回答
  •  孤城傲影
    2021-02-06 00:21

    There's nothing wrong with having the money "in flight" for a while. Make it like so:

    Account src, dst;
    
    dst.deposit(src.withdraw(400));
    

    Now just make each individual method thread-safe, e.g.

    int Account::withdraw(int n)
    {
        std::lock_guard _(m_);
        balance -= n;
        return n;
    }
    

提交回复
热议问题