Barclays Capital Interview Question
Country: India
Interview Type: In-Person
class Account
{
object _lock;
double balance;
//constructor
public Account(int Id)
{
_lock=Locker.GetLock(Id);
}
//Make this method synchronized
public Deduct(double amount)
{
lock(_lock){//deduct here}
}
//Make this method synchronized
public Add(double amount)
{
lock(_lock){//Add here}
}
}
static class Locker
{
static Dictionary<int,object> locks=new Dictionary<int,object>();
public static object GetLock(int Id)
{
if(locks.ContainsKey(id)) return locks[id];
else
{
Dictionary.Add(Id,(object)Id); return locks[id];
}
}
}
preserve the order locking
1 way in c++
recursive_mutex mx1 = ( from_acct.id< to_acct.id)? from.mx: to.mx;
recursive_mutex mx2 = ( from_acct.id< to_acct.id)? to.mx: from.mx;
lock_guard<recurisve_mutex> lk( mx1)
. . .
{
lock_guard<recursive_mutex> lk(mx2)
. . .
another:
std::lock( from.mx, to.mx)
1> The issue is that you need to lock related accounts during the transaction.
- chenlc626 March 18, 20132> You should avoid the global lock since it will lock all other threads.
3> With each account each lock, you need to take care of the order of lock other wise you got deadlock.
4> Use some unique id of the account, such as the account number, translate it into some unique lock order value, make sure Order(A)>Order(B), ORder(B)>ORder(C) ==> Order(A)>Order(C), and ORder(A)==Order(B)==> A==B. lock accounts in the transaction following the order of the ORder(account).