Fixed multithreading bugs