Fix deadlocks

Signed-off-by: Paul Brook <paul@nowt.org>
Rewrite DBThread wrapper code.

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