Determine whether the deadlock

1. Given n threads, locks n, and a set of threads of lock operation, it is determined whether a deadlock occurs.

E.g:

T    L    S

1    1    1

2    2    1

1    2    1

2    1    1

The meaning of this example is: No. 1 No. 1 of the thread lock lock success (S = 1 represents the lock, S = 0 representatives unlock), No. 2 to No. 2 thread lock to lock is successful, then the number 1 thread tries to acquire No. 2 lock, to keep waiting, No. 2 thread tries to acquire a lock No. 1, kept waiting deadlock. Now given such a set of T, L, S data, determines whether or not a deadlock.

The key question is how to determine a deadlock occurs: the whole process ends up having as many or thread is waiting for all threads in the middle of the process is waiting.

Thus the determination is a simple process: using set <int> lock status of each lock records, using map <int, int> threads, the thread of the current record and waiting waiting position. In a thread tries to acquire the lock when the lock if there is no lock, the thread acquires the lock is successful, the thread will not wait. If the lock has the lock, then join threads in the current thread, meaning that the current thread in a wait state, and record the first steps to execute, T can not continue for all subsequent operations of the current thread after this, if found thread releases the lock, then traverse the threads, to see which thread can continue to go down and so on. If the total number of threads threads is equal to the total number of threads, it means that the current deadlock, or the last threads of size still is not 0 , it means that there is still thread is waiting, it also produced a deadlock.

Guess you like

Origin www.cnblogs.com/deepllz/p/11490154.html