Thursday, 13 December 2018

Quick summary : Dead lock and race condition


DEADLOCK:

When :
two threads try to acquire series(two of more) lock in an inconsequential order.

i.e
T1 --> Object1 lock --> sleep for some time(does time consuming tasks) --> Object2 lock.
T2 --> Object2 lock --> sleep for some time(does time consuming tasks)  -> Object1 lock

the problem here is , while both threads are able to acquire some object lock and tries to acquire lock of another object, while still holding the previous object lock.



resolution :
Make sure in your code, all threads acquire the locks in a sequential manner.


T1 --> Object-1 lock --> sleep for some time(does time consuming tasks) --> Object-2
T2 --> Object-1 lock --> sleep for some time(does time consuming tasks) --> Object-2

this way if thread-1 acquire the Object-1 lock, no other threads will be able to acquire the object-1 lock.

and once thread-1 finishes doing his task, may be by acquiring object-1,Object-2 lock, it release all the locks for other threads.


RACE 

Basically, its to do with bad programming of creating a sequence of code, which are not thread safe.
ex:
out of 5 lines of code, 3 lines of code is executed by one thread and cpu scheduler, takes out your thread and allows other thread to run, allowing to change the state of object, then your previous thread come back and tries to read from line 4, assuming the state is unchanged as his last read but thread 2 has changed the state..

example :

One back account, two ATM card holder,
Check then act concept(Check the balance  and then withdraw)


No comments:

Post a Comment