Rewrite locking code

Use with statements for locking.

Signed-off-by: Paul Brook <paul@nowt.org>