Rewrite locking code

Use with statements for locking.

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

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