Fix a race condition in ctx destruction that could cause undefined behavior (deadlock observed). Add mutex unlocks to some OOM error paths.