// A state is safe iff there exists a safe sequence of grants that would allow // all threads to eventually receive their maximum resource needs. // // avail[] holds free resource count // alloc[][] holds current allocation // request[][] holds currently-blocked requests bool ResourceMgr::isDeadlocked() { int j; int toBeAvail[] = copy avail[]; bool finish[] = [false, false, false, ...]; // finish[j] is true if thread // j is guaranteed to finish while(true) { j = any threadID such that (finish[j] == false) && (forall i: request[i][j] <= toBeAvail[i]); if (no such j exists) { if (forall j: finish[j] == true) { return false; } else { return true; } } else { // Thread j *may* eventually finish and // return its current allocation to the pool. finish[j] = true; forall i: toBeAvail[i] = toBeAvail[i] + alloc[i][j]; } } }