Use defer for unlock

This commit introduces the common idiom of using defer
for releasing locks. This will make the code slightly more
readable and less error prone.