Fix threading issues and potential deadlocks