Correct some issues with multithreading and dead locks