Fixed a few bugs with multithreading and synchronization.